Fiery Phoenix Fiery Phoenix - 4 months ago 5
Python Question

Adding Digits in a Number (Need Code Explanation)

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

You should understand 2 things:

  1. n % 10 give you the rightmost digit of a number. For example: 123 % 10 = 3. More about % operator here
  2. n // 10 remove the rightmost digit of a number. For example: 123 // 10 = 12. More about // operator here

so if you repeat that process you get the desired result

Comments