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

how does it work?can anyone explain it to me?

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

how does it work?can anyone explain it to me?

in programming, explaining code like you asked, teaches very little.

break the code down, run it in small steps, line by line if you have to, so you understand what each step does, and then try to put it back together. This will teach you far more then any explanations could.

Its not that i don’t understand what this code does, i understand it perfectly, and i could explain it, but its not the right way.

i know what each line does…what i don’t understand is how it all comes together.like after the loop total is increased by remainder of x. and after that x is reassigned to the quotient of floor division of x by 10…but then it prints x so it should print the quotient instead it prints the sum…that’s what i don’t understand

it doesn’t print the sum, so it seems you don’t understand the floor division correctly.

if i have `4343 // 10`

, wat will the result be?

your original post, if you just put:

of course my reply will be what i said, because i can’t see based on your post, what you do and don’t understand, such information is very useful to put in a post

please answer this, so i can see how you do the division. You claim to know each line, so surely this shouldn’t be a problem to solve it? I don’t know for sure what the problem is until i have prove, i just suspect based on your reply that it might be the understanding of floor division

so if i run your code:

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

it gives the right output:

```
434
43
4
0
14
```

first the result of the divisions, and finally the sum (given i asked for it)

don’t forget that function only execute when called, but in the lesson the sum might be displayed of exercise validation.

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