🔁 Lesson 61: Python Recursion (Functions Calling Themselves)
1. What is Recursion?
In short → Recursion is when a function calls itself.
In other words → Recursion is when a function calls itself to solve a problem.
2. Why Use Recursion?
- Lets you break a big problem down into a handful of smaller sub-problems
- Great for tree structures and math problems (factorial, Fibonacci)
- A core technique in algorithm design (divide & conquer)
3. Summary
✅ Recursion = function calling itself
✅ You need both a base case and a recursive case
✅ Example → countdown, factorial, Fibonacci
✅ Real-world → file system, algorithms, tree structures
python
# ===== 1. Basic Recursion (Countdown) =====
def countdown(n):
if n == 0:
print("Done!")
else:
print(n)
countdown(n-1)
print("===== Countdown =====")
countdown(5)
# ===== 2. Factorial Example =====
print(f"\n===== Factorial =====")
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)
print(f"5! = {factorial(5)}") # 120
# ===== 3. Fibonacci Example =====
print(f"\n===== Fibonacci =====")
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
print(f"fibonacci(6) = {fibonacci(6)}") # 8
# ===== 4. Key Concepts =====
print(f"\n===== Key Concepts =====")
print("Base Case → Recursion ရပ်မယ့်အချက် (e.g., if n==0)")
print("Recursive Case → Function ကို ကိုယ်တိုင်ပြန်ခေါ်တဲ့အပိုင်း")
print("Stack Overflow → Base case မရေးရင် infinite recursion")
# ===== 5. Real-World Use Cases =====
print(f"\n===== Use Cases =====")
print("✅ File system traversal")
print("✅ Tree/Graph algorithms (DFS, BFS)")
print("✅ Mathematical problems")
print("✅ Divide & Conquer algorithms")You should see
===== Countdown ===== 5 4 3 2 1 Done! ===== Factorial ===== 5! = 120 ===== Fibonacci ===== fibonacci(6) = 8 ===== Key Concepts ===== Base Case → the condition that stops the recursion (e.g., if n==0) Recursive Case → the part where the function calls itself Stack Overflow → skip the base case and you get infinite recursion ===== Use Cases ===== ✅ File system traversal ✅ Tree/Graph algorithms (DFS, BFS) ✅ Mathematical problems ✅ Divide & Conquer algorithms