Print 1 to N Recursively
Print one through n with recursive calls. Students trace a zero base case, pending calls, and why printing after the recursive call reverses the return order.
1def print_1_to_n(n):2 # Base case3 if n == 0:4 return56 # Recursive case: print smaller problem first7 print_1_to_n(n - 1)8 print(n)910# Test11n = int(input("Enter n: "))12print_1_to_n(n)
Output
Enter n: 5 1 2 3 4 5
In this one
- Define a recursion base case
- Trace waiting calls
- Print during return
How it works
- 1
Return immediately at n equal to zero.
- 2
Call print_1_to_n with n - 1.
- 3
After it returns, print the current n.
Edge cases
What does n = 0 print?
What does n = 0 print?
Nothing; the base case returns immediately.
What about negative n?
What about negative n?
It never reaches this base case and eventually raises RecursionError.
What's going on
The function first calls itself with n - 1, postponing print(n). At zero it returns without printing.
The call stack records the waiting calls. As they resume, one prints before two, then three. A base case is essential: negative inputs keep decreasing away from zero, and sufficiently deep calls raise RecursionError.
What does n = 0 print? Nothing; the base case returns immediately.
What about negative n? It never reaches this base case and eventually raises RecursionError.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why is the output ascending?
Pick an answer to check it.
Question 2
What does n = 0 print?
Pick an answer to check it.
Questions people ask
What does n = 0 print?
Nothing; the base case returns immediately.
What about negative n?
It never reaches this base case and eventually raises RecursionError.
Why is the output ascending?
Printing happens after the smaller call returns.
๐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