🔁 Recursion

Functions that call themselves

← Back to Algorithms

🪆 What is recursion?

Recursion is when a function calls itself to solve a smaller version of the same problem. Think of Russian nesting dolls 🪆 — each doll contains a smaller doll, until you reach the tiniest one that contains nothing.

Every recursive function needs two parts:

  • Base case — the simplest version, where it stops calling itself.
  • Recursive case — where it calls itself on a smaller problem.

No base case = disaster!

Without a base case, the function calls itself forever and Python crashes with a RecursionError. Always make the problem get smaller and have a clear stopping point.

🔢 Classic example: countdown

def countdown(n): if n == 0: # base case print("Liftoff!") return print(n) countdown(n - 1) # recursive case (smaller!) countdown(3) # 3 # 2 # 1 # Liftoff!

✖️ Building a result: factorial

The factorial 5! = 5 × 4 × 3 × 2 × 1. Notice that 5! = 5 × 4! — a smaller copy of the same problem!

def factorial(n): if n == 1: # base case return 1 return n * factorial(n - 1) # recursive case print(factorial(5)) # 120

💡 How to trust recursion

Don't trace every call in your head! Just ask: "Is my base case correct?" and "Does each call get closer to it?" If yes, trust that the smaller call returns the right answer.

🌀 The call stack

Each recursive call waits for the one inside it to finish, stacking up like a pile of plates. When the base case returns, the stack "unwinds" back up:

factorial(3) = 3 * factorial(2) = 3 * (2 * factorial(1)) = 3 * (2 * 1) = 3 * 2 = 6

✅ What you learned

  • Recursion = a function calling itself on a smaller problem.
  • Always need a base case (stop) and a recursive case (shrink).
  • Each call waits on the call stack until the base case returns.
  • Great for problems that contain smaller copies of themselves (trees, factorials, Fibonacci).