# Digit_sum with modulo and floor divide

#1

Hi guys i just can't get the code to work. I pass the exercise but I'm not getting the desired results. For example, I got a 6 as a result instead of 17. What am I doing wrong?

``````def digit_sum2(n):

n_sum = 0

while n > 0:

n_single = n%10
n_sum = 0 + n_single
n = n//10

return n_sum

print digit_sum2(656)``````

#2

try this:

def digit_sum(n):
string_n = str(n)
total = 0
for char in string_n:
total = total + int(char)
print total

digit_sum(bill)

#3

Hi enigmatikos!

I actually have an attempt that is similar to your answer. However, I'm looking to solve this question with modulo and floor divide as well (Since it is an extra challenge given in the exercise)

Anyway I have solved my own question. It was a stupid mistake, really.

It should have been

n_sum = n_sum + n_single

n_sum = 0 + n_single

Full code as below.

def digit_sum2(n):

``````n_sum = 0

while n > 0:

n_single = n%10
n_sum = n_sum + n_single
n = n//10

return n_sum``````

print digit_sum2(656)

#4

Change

``n_sum = 0 + n_single #You are resetting n_sum to zero everytime you do this.``

to

``n_sum += n_single #You still contain the previous n_sum's value``

#5

Here is my code that is about as simple as it can be:

``````def digit_sum(x):
s = 0
while x > 0:
s += (x%10)
x //= 10
return s``````

#6

``````def digit_sum(n):