CodeMIRAI
0 XP

Recursion

2 min read 4 runnable examples Quiz included

A recursive function is one that calls itself. It solves a problem by breaking it into a smaller version of the same problem.

Countdown

Python
def countdown(n):
    if n == 0:              # base case: stop here
        print("Liftoff!")
        return
    print(n)
    countdown(n - 1)        # recursive case: a smaller problem

countdown(5)

Every recursive function needs two parts:

  1. A base case that stops the recursion.
  2. A recursive case that moves towards the base case.

Factorial

The factorial of n (written n!) is n × (n−1) × ... × 1. Notice that 5! = 5 × 4!, which is a smaller version of the same problem:

Calls go downAnswers come back upfactorial(3)3 * factorial(2)returns 6factorial(2)2 * factorial(1)returns 2factorial(1)base casereturns 1each call waits on the stack until the one below it returns
Every recursive call adds a frame; the base case stops the descent, and the answers multiply back up: 1, 2, 6.
Python
def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))
print(factorial(20))

Here is how factorial(4) unfolds:

Diagram
factorial(4) = 4 * factorial(3)
             = 4 * 3 * factorial(2)
             = 4 * 3 * 2 * factorial(1)
             = 4 * 3 * 2 * 1
             = 24

Where recursion is natural: nested data

Recursion fits data that contains smaller copies of itself, such as folders inside folders or lists inside lists:

Python
def total(items):
    result = 0
    for item in items:
        if isinstance(item, list):
            result += total(item)     # a list inside: recurse
        else:
            result += item
    return result

print(total([1, [2, 3], [4, [5, 6]], 7]))

Writing that with loops alone is surprisingly awkward.

Forgetting the base case

Without a base case, the function calls itself forever, until Python stops it:

Python
def forever(n):
    return forever(n + 1)

forever(1)

RecursionError: maximum recursion depth exceeded. Python limits recursion to about 1,000 levels deep to protect your program.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.