Search code examples
algorithmwhile-loopsum-of-digits

Algorithm to sum up all digits of a number


Can you please explain to me how this loop works? What is going on after first loop and after second etc.

def sum(n):
  s = 0
  while n:
    s += n % 10
    n /= 10
  return s

>>> print sum(123)
6

Solution

  • def sum(n):
      s = 0
      while n:
        s += n % 10
        n /= 10
      return s
    

    Better rewrite this way (easier to understand):

    def sum(n):
      s = 0 // start with s = 0 
      while n > 0: // while our number is bigger than 0
        s += n % 10 // add the last digit to s, for example 54%10 = 4
        n /= 10 // integer division = just removing last digit, for example 54/10 = 5
      return s // return the result
    

    n > 0 in Python can be simply written as n but I think it is bad practice for beginners