Print 1 to N Recursively
Print numbers from 1 to n using recursion.
IntermediatePhase 3 - Level 1: Basic RecursionExample 1 of 10
print-1-to-n-recursively.py
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
What's going on
Recursively solve smaller problem, then print current number.
Key Concepts:
Base case: n == 0, return
Recursive case: print 1 to n-1, then print n
Function calls itself with smaller value
🔗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