Python Practice › Loop Programs › Program 22

Sum of digits

EasyLoop Programs · 22 of 90

Write a Python program to calculate the sum of the digits of a number.

Advertisement
Input
40721
Output
Sum of digits: 14

Approach

  1. Take the last digit, add it, remove it; repeat.

Solution

Python
n = 40721total = 0while n > 0:    total += n % 10    n //= 10print("Sum of digits:", total)
Output
Sum of digits: 14

Line by line

Line 4

n % 10 is the current last digit.

Learn the concept

New to this topic? Read the lesson, then come back.

More loop programs

← All 90 Loop Programs

Leave a Comment