# 4/5 digit_sum error. I made the code, It gives me the right answer but Codeacademy wont accept it

#1

My code works fine (i think) but codeacademy simply won't let me pass the level, I print the result the code returns to be sure im getting what i want... and It works! But codeacademy gives me errors like "Oops, try again. Your function fails on digit_sum(1000). It returns 12 when it should return 1."

I think it should work... Can someone help me? Why does it give me an error? Does codeacademy just dont like me?

``````num = []

def digit_sum(n):
n = str(n)
for x in n:
num.append(x)
total = 0
print num           #num now contains each digit
for x in num:
total += int(x)
print total
return total        #returns the sum of the digits``````

#2

place this line:

``num = []``

inside the function

the exercise calls the function multiply times with different numbers to test if it works properly, because `num` is declared outside the function, the lists doesn't become empty for the next number/function call.

#3

Worked perfectly, thanks!!!

#4

what i don't understand is why you first append to a list, rather then adding to total directly:

``````def digit_sum(n):
total = 0
n = str(n)
for x in n:
total += int(x)
return total``````

it is basically the same, except you skip an (unnecessary) step, and saving on some lines of code

#5

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