#1

<Below this line, add a link to the EXACT exercise that you are stuck at.>

<In what way does your code behave incorrectly? Include ALL error messages.>
Your function fails on digit_sum(434). It returns 22 when it should return 11.

<What do you expect to happen instead?>
My code actually does return 11. I get no error message in the python code returner, just codeacademy says the code returns 22 when it doesnâ€™t.

``````n = 434
z = []

def digit_sum(n):
n = str(n)
for letter in n:
z.append(letter)
x = 0
for letter in z:
letter
x = x + int(letter)
return x

print digit_sum(n)
``````

#2

lets see what happens when we add a second function call:

``````n = 434
z = []

def digit_sum(n):
n = str(n)
for letter in n:
z.append(letter)
x = 0
for letter in z:
letter
x = x + int(letter)
return x

print digit_sum(n)
# second function call
print digit_sum(n)
``````

now we get 22, why? because `z` is declared outside the function, it accumulates data when the function is called multiply times

#3

Thank you!

That was much simpler than I thought it would be. I moved the z = [] to under n = str(n) and it works!

Thank you very much

#4

the other explanation is that we can import function from other scripts, so if we attempt to import function:

``````from yourscript import digit_sum
``````

we would get `z` referenced before assignment (undefined) error

#5

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