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.
1def sum_digits(n):2 # Base case3 if n == 0:4 return 056 # Recursive case7 return (n % 10) + sum_digits(n // 10)89# Test10num = 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
Call sum_digits on abs(num).
- 2
Return zero at an exhausted magnitude.
- 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.
๐Related Content
- ๐
Phase 3 - Learn Concepts
Review Phase 3 concepts and explanations
- ๐
Phase 3 - Quiz
Test your Phase 3 understanding with quiz questions
- ๐ป
Phase 3 - All Practice Problems
Explore all practice problems for Phase 3
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum