Print N to 1 Recursively
Print n down to one with recursive Python calls. Students compare work before a recursive call with work after it and identify the zero stopping condition.
1def print_n_to_1(n):2 # Base case3 if n == 0:4 return56 # Recursive case: print current, then smaller7 print(n)8 print_n_to_1(n - 1)910# Test11n = int(input("Enter n: "))12print_n_to_1(n)
Output
Enter n: 5 5 4 3 2 1
In this one
- Print before recursion
- Shrink an argument
- Stop at zero
How it works
- 1
Return without printing at zero.
- 2
Print the current n.
- 3
Request the same function for n - 1.
Edge cases
Is zero printed?
Is zero printed?
No. The base case returns before print.
What if n is negative?
What if n is negative?
The decreasing calls do not reach zero and exhaust the recursion limit.
What's going on
This function prints n before making the smaller call. The visible output therefore follows the downward journey, not the later return journey.
For three, the calls print three, two, then one before reaching zero. The call stack still stores pending returns even though no printing remains afterward. A negative input never reaches zero with this decrement and eventually raises RecursionError.
Is zero printed? No. The base case returns before print.
What if n is negative? The decreasing calls do not reach zero and exhaust the recursion limit.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Where is print placed?
Pick an answer to check it.
Question 2
Is zero printed?
Pick an answer to check it.
Questions people ask
Is zero printed?
No. The base case returns before print.
What if n is negative?
The decreasing calls do not reach zero and exhaust the recursion limit.
Where is print placed?
Before the recursive call.
๐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