Python Program to Find the Sum of Digits of a Number
easywhile loopPython
The standard way to take a number apart digit by digit — the same technique is used for reverse, palindrome and Armstrong programs.
The question
Read a positive integer and print the sum of its digits. Use a while loop with % 10 and // 10.
The code
program.py
n = int(input())
total = 0
while n > 0:
total += n % 10
n //= 10
print("Sum of digits =", total)Input
72050
Output
Sum of digits = 14
How it works
- 1n % 10 gives the last digit (1234 % 10 = 4).
- 2Add that digit to total.
- 3n //= 10 removes the last digit (1234 becomes 123).
- 4Repeat while n is greater than 0; when every digit is used, n becomes 0 and the loop ends.
Common mistakes
- Using / instead of // — n becomes 123.4 and the loop never works properly.
- Forgetting to change n inside the loop, which makes the loop run forever.
Sum of digits using a for loop and a string
Leave the input as text. A for loop over a string gives one character at a time, and int(ch) turns each one into a digit.
program.py
n = input().strip()
total = 0
for ch in n:
total += int(ch)
print("Sum of digits =", total)Input
1234
Output
Sum of digits = 10
Questions students ask
- What is 1234 // 10 in Python?
- 123. The // operator is floor division: it divides and throws away the remainder, so the last digit disappears. 1234 / 10 with a single slash gives 123.4.
- What is 1234 % 10 in Python?
- 4. The % operator gives the remainder, and the remainder after dividing by 10 is always the last digit.
- What does n //= 10 mean in Python?
- It is short for n = n // 10 — divide n by 10, drop the remainder and store the result back in n. In a digit loop it removes the last digit on every pass until n becomes 0.
Now solve a similar question yourself
A new Python question every time, checked instantly.
Preparing for NIELIT O Level?
This program is the kind asked in the M3 (Python) theory paper and the PR-3 practical exam.
