Sum of Digits in Python: for Loop, while Loop and Recursion

The sum of digits adds every decimal digit of a number. For 549, the answer is 5 + 4 + 9 = 18. Python can calculate it by iterating through a string or using % 10 and // 10.

Interactive Companion Jupyter Notebook

Run the Python examples, compare expected outputs, modify the code, and complete guided exercises.

View on GitHub Open in Google Colab
On this page — Show page sections— Hide page sections

First working example

n = "549"
my_sum = 0
for digit in n:
    my_sum += int(digit)
print("Sum of digits:", my_sum)

Output:

Sum of digits: 18

The string approach follows the original lesson and makes the digits easy to see.

Original input() example

input() returns text. Convert each character into an integer before adding it.

n = input("Enter a Number :")
my_sum = 0
for i in range(len(n)):
    my_sum += int(n[i])
print("Sum of digits in number:", my_sum)

Output:

Sum of digits in number: 18

Use a while loop and remainder

n % 10 returns the final digit, and n // 10 removes it. This is the arithmetic approach from the original page.

n = 1251
my_sum = 0
while n > 0:
    digit = n % 10
    my_sum += digit
    n //= 10
print("Sum of digits:", my_sum)

Output:

Sum of digits: 9

Write a reusable function

Return a value so other calculations can reuse it.

def digit_sum(n):
    n = abs(n)
    total = 0
    while n:
        total += n % 10
        n //= 10
    return total

for value in (0, 549, -1251):
    print(value, digit_sum(value))

Output:

0 0
549 18
-1251 9

Find the sum recursively

A recursive method processes the last digit, then the remaining number. Returning the result avoids mutable global state.

def recursive_digit_sum(n):
    n = abs(n)
    if n < 10:
        return n
    return n % 10 + recursive_digit_sum(n // 10)

print(recursive_digit_sum(1251))

Output:

9

One-line approach using sum()

A generator expression is concise, although the loop is usually clearer for beginners.

n = -7092
answer = sum(int(ch) for ch in str(abs(n)))
print(answer)

Output:

18

Handle invalid input

Convert input carefully. Negative numbers can use abs(); reject decimal points unless you deliberately want to include fractional digits.

raw = "12x"
try:
    n = int(raw)
    print(sum(map(int, str(abs(n)))))
except ValueError:
    print("Enter a whole number")

Output:

Enter a whole number

Common mistakes and troubleshooting

  • Run each example in Python 3.9 or newer. Indentation is significant in loops and functions.
  • Remember that input() returns a string. Convert and validate the value before doing arithmetic.
  • Check boundary values such as zero, negative numbers, small inputs and empty ranges.
  • When comparing outputs, note whether a code sample uses fixed values or user input.

Practice exercises

Try changing 549 to 12345, then compare the loop, recursive and one-line answers. Use the companion practice notebook for runnable examples and self-checks.

Frequently asked questions

Does the sum include a minus sign?

No. Apply abs(n) so a negative number uses the same digits as its positive counterpart.

What is the digit sum of 0?

Zero.

Which approach is best for beginners?

Start with the string for loop, then learn modulo and floor division.

Plus2Net Python Basics podcast playlist

Other related resources

Back to top ↑




Subscribe to our YouTube Channel here



plus2net.com




Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer