Sum of Digits Program in Python
Find the sum of the digits of an integer in Python using a while loop and using string conversion.
- Time
O(d), - Space
O(1) for the loop, O(d) for the string version - Hints3
- Read3 min
To find the sum of digits of a number in Python, repeat while n > 0: add n % 10 (the last digit) to a total, then remove that digit with n //= 10. For 1234 this gives 4 + 3 + 2 + 1 = 10. The string version is shorter: sum(int(d) for d in str(n)). Use abs(n) first if the number can be negative.
Problem statement
Write a sum of digits program in Python. Given an integer, print the sum of its digits. For example, the sum of digits of 1234 is 1 + 2 + 3 + 4 = 10.
Write it with a while loop, using only arithmetic, and then with a string.
An integer n.
The sum of the digits of n.
Examples
n = 1234101 + 2 + 3 + 4 = 10.
n = 9875299 + 8 + 7 + 5 = 29.
n = 00The loop does not run, so the total stays 0.
Constraints
- n can be any integer; use abs(n) for negative numbers
- Python integers have no fixed size, so long numbers also work
Think before you code
Reveal the questions to ask yourself first
- Which operator gives the last digit of a number?
- How do you throw away the last digit so the next one becomes last?
- When should the loop stop?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
Sum of digits using while loop
- Set
total = 0. - While
n > 0:digit = n % 10takes the last digit.total = total + digitadds it.n = n // 10drops it.
- Print
total.
Each pass removes exactly one digit, so the loop runs once per digit.
Digit sum in Python with a string
str(n) turns 1234 into "1234". Loop over the characters, convert each back with
int(), and add. sum(int(d) for d in str(n)) does it in one line.
| Method | Code idea | Good for |
|---|---|---|
| while loop | n % 10, n // 10 |
Exams, interviews, any language |
| String loop | for ch in str(n) |
Quick scripts, very readable |
| One line | sum(map(int, str(n))) |
When short code is fine |
Interviewers often ask for the loop version because it shows you understand % and
//. The same idea is used in reverse a number
and the Armstrong number program.
Dry run
Walk through the example step by step
n = 1234, total = 0:
n | digit = n % 10 | total | n // 10
-----+----------------+-------+--------
1234 | 4 | 4 | 123
123 | 3 | 7 | 12
12 | 2 | 9 | 1
1 | 1 | 10 | 0
n is now 0, so the loop stops. The sum of digits is 10.
Solution
Reveal the full Python solution
n = int(input("Enter a number: "))
total = 0
while n > 0:
digit = n % 10
total = total + digit
n = n // 10
print("Sum of digits:", total)Output:
Enter a number: 1234
Sum of digits: 10
Sum of digits of a number with a function
A function makes it easy to test several values, including negative numbers.
def sum_of_digits(n):
n = abs(n)
total = 0
while n > 0:
total += n % 10
n //= 10
return total
for n in [1234, 9875, 0, 7, -456]:
print(n, "->", sum_of_digits(n))
1234 -> 10
9875 -> 29
0 -> 0
7 -> 7
-456 -> 15
Without abs(n), a negative number never enters the while n > 0 loop and the
function returns 0.
String version
Here the input is kept as a string, so there is no % or // at all.
n = input("Enter a number: ")
total = 0
for ch in n:
total += int(ch)
print("Sum of digits:", total)
Enter a number: 50213
Sum of digits: 11
The one-line forms:
n = 98765
print(sum(int(d) for d in str(n)))
print(sum(map(int, str(n))))
35
35
Repeat until one digit (digital root)
Some questions ask you to keep adding the digits until one digit is left.
n = 98765
while n >= 10:
n = sum(int(d) for d in str(n))
print(n)
35
8
98765 gives 35, and 3 + 5 gives 8. See find the digital root of a number for the shortcut. The Java version of this page is find the sum of the digits of a number.
O(d), where d is the number of digitsO(1) for the loop, O(d) for the string versionReview before the interview
Common mistakes
- Using n / 10 instead of n // 10. In Python 3, / gives a float like 123.4, and the digits come out wrong.
- Writing while n >= 0. When n reaches 0 it stays 0, so the loop never ends.
- Adding the character instead of its value in the string version. total += ch fails because ch is a string; use int(ch).
- Forgetting negative numbers. With while n > 0, -456 gives 0 unless you use abs(n).
Edge cases to test
- 0 gives 0.
- A single digit such as 7 gives itself.
- Negative numbers: use abs(n) first. In the string version, "-456" would make int("-") fail.
Interview follow-ups
- How would you find the product of the digits instead of the sum?
- How would you add only the even digits of a number?
- How would you count how many digits a number has using the same loop?
Keep practising
Find the Sum of the Digits of a Number
Hints · Dry run · SolutionSolve Similar problemFind the Digital Root of a Number
Hints · Dry run · SolutionSolve Similar problemFind the Product of the Digits of a Number
Hints · Dry run · SolutionSolve Similar problemFind the Sum of the Even Digits in a Number
Hints · Dry run · SolutionSolve Related learningLoops In Programming
TutorialLearn Related learningWhat Is Python Used For
TutorialLearn Related learningPython Interview Questions
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising Python for interviews?
CodeBegun’s Python Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
