Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Sum of Digits Recursively

Add decimal digits recursively in Python. Students combine a last digit with a smaller magnitude, use abs for negatives, and trace the zero base case.

IntermediatePhase 3 - Level 1: Basic RecursionExample 10 of 10
sum-of-digits-recursively.py
1def sum_digits(n):
2 # Base case
3 if n == 0:
4 return 0
5
6 # Recursive case
7 return (n % 10) + sum_digits(n // 10)
8
9# Test
10num = int(input("Enter a number: "))
11result = sum_digits(abs(num))
12print(f"Sum of digits: {result}")

Output

Enter a number: 1234
Sum of digits: 10

In this one

  • Shrink decimal magnitude
  • Combine digit contributions
  • Handle negative input with abs

How it works

  1. 1

    Call sum_digits on abs(num).

  2. 2

    Return zero at an exhausted magnitude.

  3. 3

    Otherwise add n % 10 to sum_digits(n // 10).

Edge cases

What does zero return?

What does zero return?

Zero directly from the base case.

Does -205 produce a negative sum?

Does -205 produce a negative sum?

No. abs is applied before the helper is called.

What's going on

sum_digits separates n % 10 from the remaining n // 10. It returns that digit plus the recursive result for the remaining positions.

For 205, pending additions become five plus zero plus two plus the base value zero. abs keeps every recursive argument nonnegative. Python's call stack stores the unfinished additions; extremely long magnitudes can exceed its recursion limit.

What does zero return? Zero directly from the base case.

Does -205 produce a negative sum? No. abs is applied before the helper is called.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What makes the argument smaller?

Pick an answer to check it.

Question 2

What does zero return?

Pick an answer to check it.

Questions people ask

What does zero return?

Zero directly from the base case.

Does -205 produce a negative sum?

No. abs is applied before the helper is called.

What makes the argument smaller?

n // 10.