Keep your place in this quest

Log in or sign up for free to subscribe, follow lesson progress, and access more learning content.

Recursion is a special programming technique where a function calls itself to solve a problem.
At first, this idea can feel a bit like magic — or a little strange — but it’s a very powerful tool once you understand it.

Think of it like looking into two mirrors facing each other. You see a reflection inside a reflection, which goes on and on… until eventually, it fades out. In recursion, that “fading out” is crucial — we call it the base case, and it’s what stops the repetition.

How Recursion Works

A recursive function:

  1. Checks if it should stop — this is the base case.
  2. If not, it calls itself, but with a smaller or simpler version of the original problem.

By repeatedly breaking a problem into smaller pieces, recursion can reach the simplest possible version of the problem, solve it, and then rebuild the answer as it returns from all the calls.

Example: Factorial Calculation

Let’s take the factorial of a number.
In math, the factorial of n (written as n!) means:

n! = n × (n-1) × (n-2) × ... × 1

For example:

5! = 5 × 4 × 3 × 2 × 1 = 120

Here’s the recursive version in Python:

def factorial(n):
    if n == 0:  # base case
        return 1
    return n * factorial(n - 1)

print(factorial(5))  # 120

What’s happening here:

  • If n is 0, we’ve hit the base case — by definition, 0! equals 1.
  • Otherwise, multiply n by factorial(n - 1) (a smaller version of the same problem).
  • This repeats until we reach the base case.

Why Use Recursion?

Recursion can be:

  • Elegant and concise for problems that are naturally repetitive in structure.
  • Perfect for mathematical problems (factorials, Fibonacci numbers).
  • Essential for navigating tree-like data (file systems, family trees, game AI search).

Sometimes recursion can even replace loops, though it’s not always the most efficient option.

TIP: Recursion is often easier to understand when you think of it as “divide the problem into smaller versions of itself until you can solve it directly.”

Common Pitfalls

IMPORTANT!: Always define a base case — without it, the function will call itself forever until Python throws a RecursionError.

Troubleshooting:

  • “RecursionError: maximum recursion depth exceeded” → You didn’t reach the base case, or your base case is incorrect.
  • If recursion feels too complex for the problem, try a loop instead.

Recursion may seem mind-bending at first, but it’s just another way to make your code smarter and more adaptable. Once you’ve practiced it with a few problems, you’ll see it’s not only powerful but can also make your code surprisingly short and elegant.