Editor

Python Program to Find the Sum of Digits of a Number

Beginner · Numbers

The sum of digits of a number is what you get by adding its digits together, so the sum of digits of 4728 is 4 + 7 + 2 + 8 = 21. This program picks off the digits one at a time using the remainder and floor division operators.

Program

sum_of_digits.py
num = 4728 # or: num = int(input("Enter a number: "))
total = 0
n = abs(num) # work on a copy, ignoring any minus sign
while n > 0:
digit = n % 10 # the last digit
total = total + digit
n = n // 10 # drop the last digit
print("Sum of digits of", num, "is", total)
Output
Sum of digits of 4728 is 21

How it works

  1. n % 10 gives the last digit of n, for example 4728 % 10 is 8.
  2. That digit is added to total.
  3. n // 10 removes the last digit, so 4728 becomes 472.
  4. The loop repeats until n reaches 0, by which point every digit has been added.
  5. abs() makes a copy without the minus sign, so a negative number such as -4728 gives the same sum.

Other ways to write it

Using a string

Using a string
num = 4728
total = sum(int(digit) for digit in str(num))
print("Sum of digits of", num, "is", total)
Output
Sum of digits of 4728 is 21

str(num) turns the number into text, so each character is a digit that int() turns back into a number for sum().

Using recursion

Using recursion
def digit_sum(n):
if n < 10:
return n
return n % 10 + digit_sum(n // 10)
for num in [4728, 9, 1001]:
print("Sum of digits of", num, "is", digit_sum(num))
Output
Sum of digits of 4728 is 21
Sum of digits of 9 is 9
Sum of digits of 1001 is 2

The function adds the last digit to the digit sum of the rest, and stops when only one digit is left.

Try it yourself

Change the loop to also count how many digits the number has.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises