Error when returning


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/4?curriculum_id=4f89dab3d788890003000096#


Hello everyone, I was making the lesson and when I run the code I got a error message that says it's incorrect, even if I try with that number, I tried to print the function and it's alright

Message: Oops, try again. Your function fails on digit_sum(434). It returns 0 when it should return 11.
The console:
11
10
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
5
None

lst = []
def digit_sum(n):
    var = 0
    j = str(n)
    for i in j:        
        lst.append(int(i))
        if len(lst) == len(j):
            var = 0
            var = int(sum(lst))
    return var
print digit_sum(434)


lost = [1, 2, 3, 4] #Trying to get Logic
print sum(lost)
print lost
lost.append(5)
print lost
print lost[len(lost) - 1]

#2

the function itself should be able to calculate the digit sum, this is currently not happening because lst=[] is not inside the function. This means, your function will work once, and it can't be imported into other python scripts


#3

Thanks, man. It worked but it was a global list shouldn't work in all functions?


#4

but if we call the function multiply times:

digit_sum(123)
digit_sum(456)

lst will accumulate numbers because we don't create a new list at the beginning of our function.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.