Write Python. Understand every error.

Open the editor

Python programs · Numbers

Python program to find the sum of digits of a number

Adding the digits of a number is the classic way to learn the % and // operators.

Approach

  1. Take the last digit with n % 10 and add it to a total.
  2. Remove that digit with n // 10.
  3. Repeat until no digits remain.

The program

n = int(input())
total = 0
while n > 0:
    total += n % 10
    n //= 10
print("Sum of digits:", total)

Sample run

Input
4729
Output
Sum of digits: 22

Run this program in Py-CRAFT

How the code works

For 4729: the last digit is 9, leaving 472; then 2, leaving 47; then 7, leaving 4; then 4, leaving 0, and the loop stops. The total is 9 + 2 + 7 + 4 = 22. The same pattern reverses a number or counts its digits. A shorter way is sum(int(d) for d in str(n)), but the loop shows how numbers are built from digits.

Try changing it

Common mistakes

Learn the ideas

More programs

Share this page: