Beginner Digit Problems Python

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.

  • TimeO(d),
  • SpaceO(1) for the loop, O(d) for the string version
  • Hints3
  • Read3 min
Quick answer

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.

Digit extraction with % and //while loopString iterationsum() and int()
1

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.

Input

An integer n.

Output

The sum of the digits of n.

Examples

Example 1
Inputn = 1234
Output10

1 + 2 + 3 + 4 = 10.

Example 2
Inputn = 9875
Output29

9 + 8 + 7 + 5 = 29.

Example 3
Inputn = 0
Output0

The 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
2

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?
3

Hints

Open one at a time — try again after each.
1 Hint 1
n % 10 is the last digit. For 1234 it is 4.
2 Hint 2
n // 10 removes the last digit. 1234 // 10 is 123.
3 Hint 3
Loop while n > 0, adding each last digit to total.
4

Approach

Reveal the step-by-step approach

Sum of digits using while loop

  1. Set total = 0.
  2. While n > 0:
    • digit = n % 10 takes the last digit.
    • total = total + digit adds it.
    • n = n // 10 drops it.
  3. 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.

5

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.

6

Solution

Reveal the full Python solution
solution.py
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.

TimeO(d), where d is the number of digits
SpaceO(1) for the loop, O(d) for the string version
7

Review 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

Practising Python for interviews?

CodeBegun’s Python Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us