Recursion

Introduction

A recursive function is a function that calls itself. Each time it calls itself, a separate copy is created that has its own values for its parameters and variables. If every copy created another copy, the recursion would never end and the computer would run out of memory. So every recursive function needs at least one base case. A base case is a case where the function doesn't call itself.

Let's look at a common first example of recursion:

The if statement checks whether num is equal to zero. This is the base case. If it's true, the function does not call itself. Otherwise, it calls itself, multiplies the return value by num, and returns the result. We could also write it like this:

The else can be left out because if the condition is true, return 1 runs and the function ends before it reaches the recursive call. The other examples in this lesson use this style.

The Call Stack

When a recursive function runs, several copies of it are active at once, but only the most recent one is executing. The others are paused, waiting for a result. When a recursive call is made, the computer saves its place in the current copy so it can come back later, then starts a new copy. It saves that place on the call stack, which keeps track of all active function calls. Watch the video "Flow of execution example for recursion" to see how this works.

Check your understanding. Predict the result. Follow each call down to the base case, then work back up.

def mystery(n: int) -> int:
    if n == 0:
        return 0
    return mystery(n - 1) * 2 + n

x: int = mystery(3)
y: int = mystery(1)

Predict what each variable holds after the program finishes. The program is not run for you. Replace each None in the box below with your prediction, and give each variable a type hint, like name: type = value. Then press Run to find out if you are right. Write text in quotes, like "abc".

  • final_x is the value of x at the end
  • final_y is the value of y at the end
Hint 1

Each paused copy finishes its multiply and add only after the call below it returns.

More examples

Here's a recursive function that finds the greatest common divisor of two integers:

The base case is when b evenly divides a, in which case b is the greatest common divisor. Otherwise we make a recursive call, passing b for a and a % b for b. The function just returns whatever the recursive call returns, with no extra work.

Here's a recursive function that computes the hailstone sequence starting from a given number and counts how many steps it takes to reach 1:

Here the base case is when the sequence arrives at 1. There are two recursive cases: one if num is even and one if it is odd. We add 1 to the return value, since the current copy of hailstone takes one more step to reach 1 than the recursive call does. For example, if we start at 3, the sequence goes: 3, 10, 5, 16, 8, 4, 2, 1. Once we know how many steps it takes to go from 10 to 1, we add 1 more step to get the number of steps from 3 to 1.

Writing a Recursive Function

Recursion can feel like magic, because you're writing a function that calls the function you're still writing. The general strategy is to find a way to break the problem into a smaller problem of the same kind, plus a bit of work at the current level.

When there is no base case

A recursive function with no base case never stops calling itself. Python limits how deep the call stack can get, and when the limit is reached it stops the program with a RecursionError. Run this one and read the last line.

Nothing tells count_down to stop, so it keeps going into negative numbers until the call stack is full. The error stops the whole program, so done never prints. Add if number == 0: return as the first line of the function and run it again. This time the recursion stops and done prints.

Check your understanding. Predict the result. Name the error Python reports for this program.

def forever(number: int) -> int:
    return forever(number + 1)

forever(1)

Set error_name to the name of the error, written as a string between quotes, and give it a type hint. Python error names end in Error, and capital letters matter.

Hint 1

The function calls itself and nothing ever makes it stop.

Recall: click each blank to check yourself

Every recursive function needs a , a case where the function does not .

Explanation

Without a base case the calls never stop.

Quizzes

  1. Write a recursive function called countdown that takes a positive integer parameter and returns a string that counts down from that number to 1. For example, if 5 is passed to the function, it should return the string "5 4 3 2 1". You can use string concatenation in your recursive function to build up the return value.
Hint 1

Ask two questions. When is the answer simple enough to give without calling countdown again? Otherwise, what is the one step you take yourself, and what do you leave to a smaller countdown?

  1. Write a recursive function called countup that takes a positive integer parameter and returns a string that counts up from 1 to that number. For example, if 5 is passed to the function, it should return the string "1 2 3 4 5". You can use string concatenation in your recursive function to build up the return value.
Hint 1

This is the mirror of countdown. Which side of the smaller result does the current number go on this time?

  1. Write a recursive function called sum_countup that takes an integer parameter and returns the sum of all the integers from 1 to that number. For example if the function is passed the value 5, then it should return 15 because 1 + 2 + 3 + 4 + 5 = 15.
Hint 1

Think of the sum as this number plus the sum of everything smaller. What is the smallest case, where there is nothing smaller to add?

  1. Predict the result. Look at which side of the recursive call each number goes on.
def build_up(n: int) -> str:
    if n == 0:
        return ""
    return build_up(n - 1) + str(n)

def build_down(n: int) -> str:
    if n == 0:
        return ""
    return str(n) + build_down(n - 1)

x: str = build_up(3)
y: str = build_down(3)

Predict what each variable holds after the program finishes. The program is not run for you. Change the values below to your predictions, and write strings with quotes:

  • final_x is the value of x at the end
  • final_y is the value of y at the end
Hint 1

The recursive call returns a string, and the current number is joined on one side of it.

Projects

Practice what you learned in your own editor. Each project has its own page.