How does this work?

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 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


how does floor division work then?


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


434 will be the answer


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:


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.


oh i get it now…it stores the total and runs the whole thing again


total is increased each iteration of the loop, how else are we going to get the total?


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