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
- Take the last digit with
n % 10and add it to a total. - Remove that digit with
n // 10. - 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
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
- Count the digits instead of adding them.
- Build the reversed number with
reverse = reverse * 10 + digit.
Common mistakes
- Using
/instead of//, which gives a decimal and the loop never ends cleanly. - Using a
forloop when the number of digits is not known in advance.