Find Sum of Digits in Python

Beginner
⏱️ 7 min read
📚 Updated: May 2026
🎯 2 Code Examples
Digit math

What you'll learn

  • How to extract digits with % 10 and // 10.
  • How to sum digits using an accumulator.
  • How to handle negatives and zero correctly.

Overview

Take the last digit, add it to total, remove that digit, and repeat.

Two examples

Fixed number and user input variants.

Live preview

See digits and resulting sum instantly.

Interview focus

Clear algorithm + edge cases + complexity.

Prerequisites

Basic Python integers, loops, and input/output.

Live preview

Enter any integer (e.g. 12345 or -802).

Live result
Press "Compute".

Algorithm

1

Convert to nonnegative

n = abs(n)

2

Extract each digit

Use d = n % 10 and n //= 10

3

Add to total

total += d

📜 Pseudocode

Pseudocode
function digit_sum(n):
    n = abs(n)
    total = 0
    while n > 0:
        total += n % 10
        n //= 10
    return total
1

Sum of digits (fixed number)

python
def digit_sum(number: int) -> int:
    number = abs(number)
    total = 0
    while number != 0:
        total += number % 10
        number //= 10
    return total

number = 12345
print(f"The sum of digits of {number} is: {digit_sum(number)}")
📤 Output
The sum of digits of 12345 is: 15
2

Sum of digits (user input)

python
def digit_sum(number: int) -> int:
    number = abs(number)
    total = 0
    while number != 0:
        total += number % 10
        number //= 10
    return total

number = int(input("Enter a number: ").strip())
print(f"Sum of digits: {digit_sum(number)}")

❓ FAQ

Take last digit with n % 10, add it to total, and remove last digit with n //= 10 until n becomes 0.
In base 10, dividing by 10 leaves a remainder from 0 to 9, which is the last digit.
Use abs(n) so the sign does not affect digit sum.
1 + 2 + 3 + 4 + 5 = 15.
O(d), where d is number of digits.

🔄 Input / output examples

InputDigit sumExplanation
12345151+2+3+4+5
-802108+0+2
00special case

Edge cases and pitfalls

n = 0

Return 0

Sum of digits of 0 is 0.

Negative input

Use abs()

Most tasks ignore sign for digit sum.

Large values

Digit-linear work

Each loop handles one digit.

⏱️ Time and space complexity

ApproachTimeExtra space
Digit loopO(d)O(1)

Summary

  • Use modulo and floor division to process digits.
  • Handle negatives via abs().
  • Complexity is linear in number of digits.
Did you know?

Digit sum helps with divisibility tests: a number is divisible by 3 (or 9) exactly when its digit sum is divisible by 3 (or 9).

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful