Increasing + Decreasing in One Function
Print increasing then decreasing values with one recursive Python function. Students trace work before and after a call and avoid printing the peak twice.
1def print_inc_dec(n, current=1):2 # Base case3 if current > n:4 return56 # Print increasing7 print(current, end=" ")8 # Recurse9 print_inc_dec(n, current + 1)10 # Print decreasing (after recursion)11 if current < n:12 print(current, end=" ")1314# Test15n = int(input("Enter n: "))16print_inc_dec(n)17print()
Output
Enter n: 5 1 2 3 4 5 4 3 2 1
In this one
- Do work before and after calls
- Avoid a doubled peak
- Understand saved arguments
How it works
- 1
Print current, then recurse for current + 1.
- 2
Return when current exceeds n.
- 3
Print saved current again only when below n.
Edge cases
Why is n not printed twice?
Why is n not printed twice?
The return-side print requires current < n.
What happens for n = 0?
What happens for n = 0?
No values print; only the caller's newline remains.
What's going on
current increases from one until it exceeds n. Each call prints current before requesting the next value.
During return, the call prints current again only when it is below n. For n equal to three, the line is 1 2 3 2 1. The call stack stores each current value until its after-call work is finished.
Why is n not printed twice? The return-side print requires current < n.
What happens for n = 0? No values print; only the caller's newline remains.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is printed for n = 2?
Pick an answer to check it.
Question 2
Why is n not printed twice?
Pick an answer to check it.
Questions people ask
Why is n not printed twice?
The return-side print requires current < n.
What happens for n = 0?
No values print; only the caller's newline remains.
What is printed for n = 2?
1 2 1.
๐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