← Learning Hub
Beginner

Recursion

A recursive function calls itself on a smaller version of the problem. Every recursive function needs a base case - a point where it stops.

Recursion solves a problem by solving smaller copies of the same problem - like opening nested boxes until you reach the smallest one. It's natural for trees, folders, and "try every possibility" problems. Every recursive function needs a base case that stops it.

Example
You can edit this code.

How it runs

factorial(3) waits for factorial(2), which waits for factorial(1) = 1. Then the answers come back: 2 × 1 = 2, then 3 × 2 = 6. Each waiting call sits on the call stack.

More examples

Example
You can edit this code.

Memoisation

Plain recursive Fibonacci repeats the same work again and again (O(2ⁿ)). Remembering answers makes it O(n).

Example
You can edit this code.
Python stops very deep recursion (about 1,000 calls) with a RecursionError. For deep problems, use a loop or your own stack.
Key points
  • A recursive function calls itself on a smaller input.
  • Always define a base case.
  • Recursion uses stack memory; very deep recursion can fail.

📝 Test yourself

1. What does every recursive function need?
2. What does memoisation do?
3. Fill in what factorial(1) should return as the base case:
if n <= 1: return