DocsHub
PythonBeginner

Sum of Digits

Learn how to find the sum of all digits in a number in Python.

Sum of Digits

Problem

Given a number, find the sum of all its digits.

Input:  1234
Output: 10   (1 + 2 + 3 + 4)

Input:  9875
Output: 29   (9 + 8 + 7 + 5)

Input:  -456
Output: 15   (4 + 5 + 6)

Input:  0
Output: 0

Logic

  1. If the number is negative, work with the positive version
  2. Extract each digit one by one
  3. Add each digit to the total
  4. Return the total

Flow

Yes No Yes No Start total = 0 Is number negative? n = abs n Keep as is n greater than 0? digit = n % 10get last digit total += digit n = n // 10remove last digit Return total

Solution 1 — using a loop and math

Extract each digit using % 10 and remove it using // 10. Classic approach — no strings involved.

def sum_of_digits(n):
    # handle negative numbers
    n = abs(n)

    total = 0

    while n > 0:
        digit = n % 10    # get the last digit
        total += digit    # add it to total
        n = n // 10       # remove the last digit

    return total


print(sum_of_digits(1234))   # 10
print(sum_of_digits(9875))   # 29
print(sum_of_digits(-456))   # 15
print(sum_of_digits(0))      # 0

Code Execution — Solution 1

Trace through sum_of_digits(1234):

Loopndigit = n % 10total += digitn = n // 10
Start12340
1st123440 + 4 = 4123
2nd12334 + 3 = 712
3rd1227 + 2 = 91
4th119 + 1 = 100
End0loop stops

Result: 10

Now trace sum_of_digits(9875):

Loopndigit = n % 10totaln = n // 10
Start98750
1st987555987
2nd98771298
3rd988209
4th99290
End0loop stops

Result: 29

n % 10 gives the last digit of any number. 1234 % 10 = 4. Then n // 10 removes that last digit. 1234 // 10 = 123. These two operations let you walk through every digit from right to left.


Solution 2 — using string conversion

Convert the number to a string, loop through each character, convert each back to an integer, and add them up.

def sum_of_digits(n):
    # handle negative numbers — abs() removes the minus sign
    n = abs(n)

    total = 0

    # str(n) converts number to string — "1234"
    # each char is one digit — "1", "2", "3", "4"
    for char in str(n):
        total += int(char)   # convert each character back to int and add

    return total


print(sum_of_digits(1234))   # 10
print(sum_of_digits(9875))   # 29
print(sum_of_digits(-456))   # 15
print(sum_of_digits(0))      # 0

Code Execution — Solution 2

Trace through sum_of_digits(-456):

abs(-456)456 str(456)"456"

Loopcharint(char)total
Start0
1st"4"44
2nd"5"59
3rd"6"615
Done15

Solution 3 — using sum() and a generator

The most concise solution. Convert to string, convert each character to int, pass everything to sum().

def sum_of_digits(n):
    # abs() handles negatives
    # str() converts to string
    # int(char) converts each character to integer
    # sum() adds them all up
    return sum(int(char) for char in str(abs(n)))


print(sum_of_digits(1234))   # 10
print(sum_of_digits(9875))   # 29
print(sum_of_digits(-456))   # 15
print(sum_of_digits(0))      # 0

Code Execution — Solution 3

Trace through sum_of_digits(9875):

StepCodeResult
absabs(9875)9875
strstr(9875)"9875"
generatorint(char) for char in "9875"9, 8, 7, 5
sumsum(9, 8, 7, 5)29

Solution 4 — using recursion

Call the function on itself — each call strips one digit and adds it to the result of the next call.

def sum_of_digits(n):
    # handle negative numbers
    n = abs(n)

    # base case — single digit number, just return it
    if n < 10:
        return n

    # recursive case:
    # n % 10 → last digit
    # sum_of_digits(n // 10) → sum of all remaining digits
    return (n % 10) + sum_of_digits(n // 10)


print(sum_of_digits(1234))   # 10
print(sum_of_digits(9875))   # 29
print(sum_of_digits(-456))   # 15
print(sum_of_digits(0))      # 0

Code Execution — Solution 4

Trace through sum_of_digits(1234):

Each call strips the last digit and passes the rest to the next call:

sum_of_digits(1234)
  = (1234 % 10) + sum_of_digits(123)
  = 4 + sum_of_digits(123)
        = 3 + sum_of_digits(12)
              = 2 + sum_of_digits(1)
                    = 1   ← base case, 1 < 10
              = 2 + 1 = 3
        = 3 + 3 = 6
  = 4 + 6 = 10

Result: 10

Recursion breaks the problem into smaller versions of itself. Each call handles one digit and passes the rest to the next call. The base case n < 10 stops the recursion — without it the function would call itself forever.


Which solution to use?

SolutionHowBest when
Solution 1Loop + % 10 and // 10Understanding digit extraction
Solution 2String conversion + loopReadable, easy to follow
Solution 3sum() + generatorClean one-liner
Solution 4RecursionUnderstanding recursive thinking

Output

10
29
15
0

On this page