# Practice makes perfect 4. digit_sum

#1

My code isn't behaving as I expected it would. I wanted to create a program which returns the sum of the numbers in a number, for example 1234 becomes 1+2+3+4. I know there's easier ways to do this, but I want to do is this way for practice. A point in the right direction would be much appriciated!

I want the code to print the total variable after the while loop is done.

"Your function fails on digit_sum(434). It returns 430 when it should return 11." I don't understand why it prints this instead.

What i want the code to do is check if n*10 > x, then add the value of (n%x)/z to total, then replace n with the value of n -(n%x) and then z with z*10 and x with x*10, and go until n*10 <= x is not correct, then print total.

``````def digit_sum(n):
x = 10
z = 1
total = 0
while n*10 >= x:
print (n % x) / z
total =+ (n % x)/z
return n - (n % x)
return x * 10
return z * 10
else:
print total

``````

#2

Any `return` statement ends the function. Also this line needs the operator `+=`, as `=+` is wrong. But, you're almost right.

#3

Thanks, that was stupid of me.

Now my code looks like this

``````def digit_sum(n):
x = 10
z = 1
total = 0
while n*10 >= x:
print (n % x) / z
total += (n % x)/z
n = n - (n % x)
n = n - (n % x)
x = x * 10
z = z * 10
else:
print total
Remember that you can use `*=`, `/=` and `-=` as well, also, that `else` statement is unnecessary.