The sum of digits of a number is the total you get when you add all its digits. For example, the digits of 1234 are 1, 2, 3 and 4, and their sum is 10. In this lesson you will find the sum of digits with a while loop, with a string, and with recursion.
Run the code in our online Python compiler. The compiler does not take keyboard input, so the examples use fixed values.
Method 1: using a while loop
Take the last digit with n % 10, add it to a running total, and remove it with n // 10. Repeat until no digits are left.
def sum_of_digits(n):
total = 0
while n > 0:
total += n % 10
n = n // 10
return total
print(sum_of_digits(1234))
print(sum_of_digits(999))
print(sum_of_digits(0))
print(sum_of_digits(1000))Output:
10 27 0 1
How it works
Here is the loop for n = 1234:
Step | n % 10 (last digit) | total | n after the step |
|---|---|---|---|
1 | 4 | 4 | 123 |
2 | 3 | 7 | 12 |
3 | 2 | 9 | 1 |
4 | 1 | 10 | 0 |
When n becomes 0, the loop stops, and the total is the sum of the digits.
Method 2: using a string
Convert the number to a string, turn each character back into a number, and add them up with sum().
n = 1234
print(sum(int(digit) for digit in str(n)))Output:
10This is the shortest solution. It is easy to read, but it works with text instead of the arithmetic idea of the first method.
Method 3: using recursion
The sum of digits of n is the last digit plus the sum of digits of the rest of the number.
def sum_of_digits(n):
if n == 0:
return 0
return n % 10 + sum_of_digits(n // 10)
print(sum_of_digits(1234))Output:
10The base case is n == 0, where the sum is 0. Each call handles one digit.
Which method should you use?
Method | Best for |
|---|---|
while loop | Exams and interviews |
String and sum() | The shortest code |
Recursion | Learning how recursion works |
Take the number from the user (on your computer)
n = int(input('Enter a number: '))
print('Sum of digits:', sum_of_digits(n))Our online compiler does not support input() yet, so use a fixed value there.
Common mistakes
- Forgetting n = n // 10. The loop never ends.
- Using / instead of //. Normal division gives a decimal number.
- Starting total at 1. It must start at 0.
- Adding the characters of a string. Without int(), digit is text, and sum() raises a TypeError.
Practice questions
- Find the sum of the digits of 98765.
- Check whether the sum of the digits of a number is even or odd.
- Keep adding the digits until you get a single digit (for example, 987 gives 24, then 6).
- Find the product of the digits of a number.
- Find the largest digit of a number.
FAQs
What is the sum of the digits of 1234?
1 + 2 + 3 + 4 = 10.
How do I find the sum of digits without converting to a string?
Use a while loop with n % 10 and n // 10.
Does this work for negative numbers?
The loop above returns 0 for a negative number. Use abs(n) to find the sum of the digits of its absolute value.
