Digit_sum - why doesn't this code work?


#1

Can someone please explain why this doesn’t work?

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

If I write:

def digit_sum(n):
n = str(n)
for x in n:
x = int(x)
print x

it will return the 0434 in the window, so when I use the result += x - why won’t it add them all together?


#2

Set this before the loop.


#3

Ahh ok - that’s what I was kind of thinking - it was only totaling the sum of that 1 loop correct vs. add all of the iterations to result?


#4

Correct. Initialization is always done before the loop so we get an accurate result.


#5

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