4. digit_sum - Code works but it doesn't..?


#1

I don't understand why my code is coming up with an error...

digit_list = []

def digit_sum(n):
    string = str(n)
    for num in string:
        num = int(num)
        digit_list.append(num)
    sum_list = sum(digit_list)
    return sum_list

digit_sum(434)

It works fine when I print sum_list, but I get the error:

Your function fails on digit_sum(434). It returns 22 when it should return 11.

Even though it prints 11 when I try it.


#2

Try to refresh the page, your code seems ok ^^


#3

Tried that, still not working :confused:


#4

Did you try to put the list digit_list into the function? :slightly_smiling:

like:

def digit_sum(n):
    digit_list = []
    string = str(n)
    for num in string:
        num = int(num)
        digit_list.append(num)
    sum_list = sum(digit_list)
    return sum_list

because if you call the function again, it will add the new number to the old one, since you didnt renew your list.

For example:

print digit_sum(434)
it will give you 11
but if you call it again:
print digit_sum(123)
it will give you 17, instead of 6, because 1,2,3 got appended to the old list.
since you didn't renew your list when you called the function again :smiley:

and sorry for seeing it so late :frowning:


#6

That worked!

Thanks a lot ^_^