Fiery Phoenix - 1 year ago 47

Python Question

I came across this code segment elsewhere. It simply adds all the digits in a given number:

`def sumDigits(n):`

sum = 0

while n > 0:

sum += n % 10

n //= 10

return sum

Problem is, I don't get the logic behind it at all. In particular, I don't get exactly what the loop does:

`while n > 0:`

sum += n % 10 # Why n % 10?

n //= 10 # Again, not sure why we divide the number by 10

Could someone provide me with an example of how the algorithm works?

Thanks!

Answer Source