Python Practice › Loop Programs › Program 22
Sum of digits
Write a Python program to calculate the sum of the digits of a number.
Input
40721
Output
Sum of digits: 14
Approach
- Take the last digit, add it, remove it; repeat.
Solution
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.