Numbers · beginner
Python Program to Find the Sum of Digits of a Number
Find the sum of the digits of a number in Python with a while loop using % and //, and in one line with sum() and map(), handling negative numbers too.
- while loop
- modulo %
- floor division //
- abs()
The sum of digits of 4721 is 4 + 7 + 2 + 1 = 14. The arithmetic method is worth knowing because it shows how to take a number apart: n % 10 is the last digit, and n // 10 removes it.
The program
def digit_sum(n):
n = abs(n)
total = 0
while n > 0:
total += n % 10
n //= 10
return total
print(digit_sum(4721))
print(digit_sum(-905))
print(digit_sum(0))14
14
0How it works
- abs(n) removes the minus sign, so -905 is treated like 905.
- n % 10 is the last digit (4721 % 10 is 1), which is added to total.
- n //= 10 divides by 10 and drops the remainder, removing the last digit (4721 becomes 472).
- When no digits are left, n is 0 and the loop stops. For 0 itself the loop never runs and the sum is 0.
Watch it run line by line
Inside digit_sum, watch n shrink (4721, 472, 47, 4, 0) while total grows (1, 3, 10, 14). The highlighted values show exactly which variable each line changes.
“Visualize step by step” opens the program in the Python Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: One line with str and map
Converting to a string and adding up int() of each character gives the same result. It is shorter and fine for everyday code.
Common mistakes
- Using / instead of //: 4721 / 10 is 472.1, so the loop takes many more steps and the sum is wrong.
- Forgetting abs(): with a negative number the while n > 0 loop never runs, so the sum is 0.
- str(n) on a negative number includes "-", and int("-") raises ValueError.
Try it yourself
- Reverse a number with the same loop: build the result with result = result * 10 + n % 10.
- Keep adding the digits until a single digit is left (the digital root): 4721 → 14 → 5.
Open the program in the Python Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 Python examples, or write your own program in the online Python Compiler.