Home / Python / Example programs / Loops and numbers

Python program: Sum of the digits of a number

Add up the digits of a whole number, with maths and with strings.

The code

n = 98765

total, x = 0, n
while x > 0:
    total += x % 10      # the last digit
    x //= 10             # drop the last digit
print("maths:  ", total)

print("strings:", sum(int(d) for d in str(n)))

Output

maths:   35
strings: 35

How it works

% 10 gives the last digit and // 10 removes it. The string version turns the number into text and converts each character back.

Python features used

Learn the ideas behind it in the free lesson Loops.