How does this work?


#1
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?


#2

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.


#3

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


#4

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


#5

how does floor division work then?


#6

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


#7

434 will be the answer


#8

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.


#9

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


#10

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


#11

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