Odd Numbers 1-N Recursively
Print odd integers through n with a recursive Python function. Students follow the zero base case, upward return order, and a remainder-based output filter.
1def print_odd(n):2 # Base case3 if n == 0:4 return56 # Recursive case7 print_odd(n - 1)8 # Print if odd9 if n % 2 != 0:10 print(n)1112# Test13n = int(input("Enter n: "))14print_odd(n)
Output
Enter n: 10 1 3 5 7 9
In this one
- Combine recursion and parity
- Delay output
- Recognize recursion limits
How it works
- 1
Return when n is zero.
- 2
Call the helper for n - 1 first.
- 3
Print the current n only if it is odd.
Edge cases
What does n = 2 print?
What does n = 2 print?
Only one.
Why not allow negative n here?
Why not allow negative n here?
Repeated subtraction moves farther from the zero base case.
What's going on
Each call waits for n - 1 before deciding whether to print its own n. A nonzero remainder modulo two selects odd values.
For five, the resumed calls print one, three, and five. Even calls still exist but print nothing. Python stores the pending calls on its call stack; negative inputs or excessive depth can exceed the recursion limit.
What does n = 2 print? Only one.
Why not allow negative n here? Repeated subtraction moves farther from the zero base case.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which condition selects an odd value?
Pick an answer to check it.
Question 2
What does n = 2 print?
Pick an answer to check it.
Questions people ask
What does n = 2 print?
Only one.
Why not allow negative n here?
Repeated subtraction moves farther from the zero base case.
Which condition selects an odd value?
n % 2 != 0.
๐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