Python programs / Numbers / Sum of digits

Python Program to Find the Sum of Digits of a Number

Beginner Numbers

Adds up the digits of a number, taking the last digit with % 10 and removing it with // 10 until none are left.

The sum of the digits of 4728 is 4 + 7 + 2 + 8 = 21. This program finds it with arithmetic only: number % 10 is the last digit, and number // 10 is the number without it. The same two steps are behind many digit programs, such as reversing a number or checking a palindrome.

Program

def sum_of_digits(number):
    """The sum of the digits of a number that isn't negative."""
    total = 0
    while number > 0:
        total += number % 10  # the last digit
        number //= 10         # remove the last digit
    return total


print("Sum of digits of 4728:", sum_of_digits(4728))
print("Sum of digits of 3050:", sum_of_digits(3050))

Open in the editor Download sum_of_digits.py

Output

Sum of digits of 4728: 21
Sum of digits of 3050: 8

How it works

  1. total starts at 0 and collects the digits.
  2. The loop runs while the number has digits left. Each round removes one, so it ends when the number reaches 0.
  3. number % 10 is the remainder after dividing by 10, which is the last digit: 4728 % 10 is 8. It's added to total.
  4. // divides and drops the remainder, which removes the last digit: 4728 // 10 is 472.
  5. When no digits are left, total holds their sum, and the function returns it.
  6. The program adds up the digits of 4728 and 3050. The zeros in 3050 add nothing, but the loop still takes them off one by one.

For 4728:

number number % 10 total number // 10
4728 8 8 472
472 2 10 47
47 7 17 4
4 4 21 0

Other ways to write it

With str()

As text, the number's digits are its characters. int() turns each one back into a number and sum() adds them up (strings).

def sum_of_digits(number):
    return sum(int(digit) for digit in str(number))

print(sum_of_digits(4728))

With recursion

The sum of the digits is the last digit plus the sum of the digits of the rest: the same problem with a smaller number, so the function can call itself (recursion).

def sum_of_digits(number):
    if number == 0:
        return 0
    return number % 10 + sum_of_digits(number // 10)

print(sum_of_digits(98765))

Try it yourself

  • Try 0, and 987654321, whose digits add up to 45.
  • For a negative number the loop never runs, so the function returns 0. Make it work with abs(): the digits of -472 add up to 13.
  • Keep adding the digits until one digit is left (the digital root): 4728 gives 21, then 3.
  • A number is divisible by 3 when its digit sum is. Check it on 4728: 21 is divisible by 3, and so is 4728 (3 ร— 1576).

More numbers programs

Share this program