PythonMastery

Sum of digits of a number in Python

Add up the digits of a number with % and // in a while loop, and with a string. Works for negative numbers too.

The sum of the digits of 9875 is 9 + 8 + 7 + 5 = 29. This page shows the arithmetic way (with % and //) and the string way.

The program

python
n = int(input("Enter a number: "))

number = abs(n)
total = 0
while number > 0:
    total += number % 10
    number //= 10

print(f"Sum of digits of {n} = {total}")

Typed in this example: 9875. Press Run to type your own.

output
Enter a number: 9875
Sum of digits of 9875 = 29

How it works

Another way: with a string

str(n) turns the number into text, and a loop over a string gives one character at a time:

python
n = -9875

total = sum(int(digit) for digit in str(abs(n)))
print(total)
output
29

int(digit) turns each character, such as "9", back into a number before it is added. The string way is shorter. The arithmetic way is worth knowing, because the same % 10 and // 10 steps are used to reverse a number and to count digits.

Learn the idea: Loops: for, while, and the Pythonic Patterns, Operators & Expressions