Codiqo

Learn Python · lesson 49 of 60 · about 8 minutes

Functions That Call Themselves

Solve a problem by solving a smaller copy of it: a function that calls itself.

What you'll learn

  • Spot the base case and the recursive case
  • Write a countdown with recursion
  • Work out factorial recursively

A timer for Sam

Sam wants a timer in the assistant: type how many seconds, and it counts them down, 3, 2, 1, then Time's up!. Anything over 10 seconds gets a polite no. A loop could do the counting, but this unit is about another way: a function that calls itself. countdown(3) prints 3 and then calls countdown(2), and when the count gets down to 0 it prints Time's up! and stops.

A smaller copy of the same job

A recursive function calls itself. Each call handles one small piece and hands the rest to another call.

Every recursive function needs two parts:

  • a base case: the simplest version, answered straight away with no more calls
  • a recursive case: do a little, then call the function again on something smaller

Counting down

def countdown(n):
    if n == 0:
        print("Lift off!")
    else:
        print(n)
        countdown(n - 1)

countdown(3)

Output

3
2
1
Lift off!

Returning a value

A recursive function can also build up an answer. The factorial of 4 is 4 × 3 × 2 × 1, which is the same as 4 × (the factorial of 3). Each call returns its result to the call that made it.

Factorial

def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)

print(factorial(4))
print(factorial(5))

Output

24
120

A base case that catches everything

Sam's timer uses if n <= 0: rather than if n == 0:. Counting down from 3 lands on 0 either way, but if Sam types 0 or a negative number, == 0 would never match and the calls would go on and on. <= 0 catches every number at the bottom, so the countdown always stops.

Tip

Each call must move closer to the base case (here n gets 1 smaller every time). If it never reaches it, the calls go on until Python gives up.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.