Sum of Digits in Python

Compute the sum of digits of an integer using a loop.

BeginnerLoop ProgramsExample 4 of 25
sum-of-digits.py
1# Program to find the sum of digits of a number
2
3num = int(input("Enter an integer: "))
4
5total = 0
6temp = abs(num)
7
8while temp > 0:
9 digit = temp % 10
10 total += digit
11 temp //= 10
12
13print("Sum of digits of", num, "is", total)

Output

Enter an integer: 1234
Sum of digits of 1234 is 10

What's going on

We repeatedly extract the last digit with % 10, add it to a running total, and remove it using integer division // 10.

After this program

If the idea is still fuzzy, read Day 9: Loops and Iteration in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 loop programs, or see every topic on Python exercises.