Sum of First N Natural Numbers Recursively
Sum one through n using recursive Python returns. Students trace a zero base case and see how pending additions combine after the smallest call finishes.
1def sum_natural(n):2 # Base case3 if n == 0:4 return 056 # Recursive case7 return n + sum_natural(n - 1)89# Test10n = int(input("Enter n: "))11result = sum_natural(n)12print(f"Sum: {result}")
Output
Enter n: 5 Sum: 15
In this one
- Return a smaller sum
- Use an additive base value
- Trace the call stack
How it works
- 1
Return zero for zero terms.
- 2
Request the sum through n - 1.
- 3
Add n to the returned smaller sum.
Edge cases
What does n = 0 return?
What does n = 0 return?
Zero.
Does the function print each term?
Does the function print each term?
No. It returns values; the outer print displays the total.
What's going on
sum_natural(n) returns n plus the sum of the smaller range. At zero, returning zero gives the addition a neutral endpoint.
For three, the expression becomes 3 + 2 + 1 + 0, then resolves to six as calls return. The call stack holds pending additions. Negative inputs never reach zero through subtraction, and deep inputs can raise RecursionError.
What does n = 0 return? Zero.
Does the function print each term? No. It returns values; the outer print displays the total.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What combines the current n with the smaller result?
Pick an answer to check it.
Question 2
What does n = 0 return?
Pick an answer to check it.
Questions people ask
What does n = 0 return?
Zero.
Does the function print each term?
No. It returns values; the outer print displays the total.
What combines the current n with the smaller result?
Addition.
๐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