Skip to contentSkip to navigation

Module 05 · Lesson 03

Recursion & the Call Stack

Understand where variables live, local or global, and solve problems with functions that call themselves: base cases, recursive cases, the call stack and RecursionError.

  • About 9 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Where names live
  • Call yourself
  • The base case
  • Watch calls stack up

Functions that call themselves

First, where names live. Then a powerful trick: a function that solves a big problem by calling itself on a smaller one.

  • Local names

    A name made inside a function exists only during that call. Outside names can be read inside.

  • Recursion

    A function that calls itself, each time on a smaller piece of the problem.

  • Base case

    The simple case that answers without calling again, such as if n == 1: return 1. Without it, it never stops.

  • Call stack

    Each call waits for the one it made. The answers come back in reverse order.

Things that contain smaller copies of themselves

Recursion fits anything built from smaller versions of the same shape.

  • FoldersA folder holds files and more folders, which hold more folders. Counting files is recursive.
  • Nesting dollsOpen a doll and find a smaller doll, until the tiniest one, the base case.
  • Fractal artA tree drawn as a trunk with two smaller trees on top, again and again.
  • Puzzle solversTry a move, then solve the smaller puzzle that is left.

The recursive line

This line is the heart of a factorial function. Tap each part to see its job.

Part 1 of 5

Tap any part of the code below, or press Next.1 of 5 explored

send back:The answer goes back to whichever call is waiting for it.

Smaller and smaller

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Count down

Each call prints one number, then calls itself with a smaller one.

Your turn: Move print(n) below the recursive call. Predict the new order first.

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

countdown(5)
Output
Press Run to see what it prints.

Watch calls stack up

Press Step to run one line at a time. Each call waits for the smaller one inside it.

Ready. Press Step to run the first line.

  1. def factorial(n):
  2. if n == 1:
  3. return 1
  4. return n * factorial(n - 1)
  5. answer = factorial(3)
  6. print(answer)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.Adding down to 0: what prints?

def f(n):
    if n == 0:
        return 0
    return n + f(n - 1)

print(f(4))

0 of 6 answered

Common recursion misconceptions

Each card is something beginners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Scope and functions that call themselves

Local and global scope

The scope of a variable is the part of the program where its name can be used. A variable created at the top level of a program, outside every function, is global: it can be read anywhere in the file. A variable created inside a function, including each parameter, is local to that call. It appears when the call starts and disappears when the call returns.

Try it 1: edit me, then Run
greeting = "Hello"          # global

def welcome(name):
    message = f"{greeting}, {name}"   # message and name are local
    return message

print(welcome("Ana"))
print(greeting)             # fine
# print(message)            # NameError: message only existed inside the call
Output
Press Run to see what it prints.

When Python looks up a name inside a function, it checks the function's local names first, then the global names, then the built-in names such as print and len. The first match wins. This means a local variable with the same name as a global one hides the global inside that function, without changing it.

Try it 2: edit me, then Run
count = 10

def reset():
    count = 0               # a new local count; the global is untouched
    return count

print(reset(), count)       # 0 10
Output
Press Run to see what it prints.

The global keyword, and why to avoid it

Assigning to a name inside a function always makes it local, unless you declare global name first. Reading a global and then assigning to the same name in one function raises UnboundLocalError, because Python decides the name is local for the whole function.

Try it 3: edit me, then Run
score = 0

def add_point():
    global score
    score += 1

add_point()
print(score)                # 1
Output
Press Run to see what it prints.

This works, but functions that change globals are hard to reason about: to understand any line, you need to know every function that might have changed the value. The better habit is to pass values in as arguments and return the new value: score = add_point(score). Use globals for constants, such as TAX_RATE, and keep everything that changes inside function arguments and return values.

Recursion

A recursive function is one that calls itself. That sounds circular, but it works as long as every call is a smaller version of the problem and some version is small enough to answer directly. Every recursive function has two parts:

  • a base case, a simple input answered without another call, which stops the recursion;
  • a recursive case, which calls the function on a smaller input and uses the result.
Try it 4: edit me, then Run
def countdown(n):
    if n == 0:              # base case
        print("Liftoff!")
        return
    print(n)
    countdown(n - 1)        # recursive case: smaller n

countdown(3)
Output
Press Run to see what it prints.

This prints 3, 2, 1 and Liftoff!. Each call handles one number and hands the rest of the job to a call with n - 1, until n reaches 0.

Recursion that returns a value

Factorial is the classic example. The factorial of 4, written 4!, is 4 x 3 x 2 x 1 = 24. Notice that 4! is 4 x 3!, and 3! is 3 x 2!, and so on, down to 1! which is simply 1.

Try it 5: edit me, then Run
def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

print(factorial(4))         # 24
Output
Press Run to see what it prints.

The call stack

Each call gets its own set of local variables, kept in a frame. Python keeps the active frames on the call stack. When factorial(4) calls factorial(3), the first call pauses, waiting for an answer, and a new frame with its own n goes on top of the stack. The stack grows until the base case is reached:

factorial(4) waits for factorial(3), which waits for factorial(2), which waits for factorial(1), which returns 1. Then the stack unwinds: factorial(2) returns 2 x 1 = 2, factorial(3) returns 3 x 2 = 6, and factorial(4) returns 4 x 6 = 24. Four separate variables called n existed at once, one in each frame, which is exactly why local scope matters for recursion.

When recursion goes wrong

If the base case is missing, or the recursive case does not move towards it, the function keeps calling itself and the stack keeps growing. Python stops it after about 1,000 levels with RecursionError: maximum recursion depth exceeded. When you see that error, check two things: is there a base case, and does every recursive call get closer to it? A call like factorial(n) instead of factorial(n - 1) never gets closer.

The limit also means recursion is not suitable for very deep problems, such as counting down from a million. A loop handles that easily.

Recursion on lists and strings

Recursion fits any problem that can be split into a first piece and the rest. Slicing gives the rest.

Try it 6: edit me, then Run
def total(items):
    if not items:           # empty list: base case
        return 0
    return items[0] + total(items[1:])

def reverse(text):
    if len(text) <= 1:
        return text
    return reverse(text[1:]) + text[0]

print(total([4, 5, 6]), reverse("abc"))   # 15 cba
Output
Press Run to see what it prints.

Recursion or a loop?

Anything recursion can do, a loop can also do, and for simple counting or summing a loop is usually clearer and has no depth limit. Recursion shines when the data is itself nested: a folder holds files and other folders, a family tree holds people who have children, a menu holds items and sub-menus. For those, a function that handles one level and calls itself for the level below is often much shorter than the loop version. When you write one, always write the base case first.

Syntax

The general shape of the statements in this lesson.

syntax.py
x = 1                    # global
def f():
    y = 2                # local to each call
    global x             # only if you must assign to a global
def rec(n):
    if n == 0:           # base case first
        return 0
    return n + rec(n - 1)  # smaller input each time
# RecursionError: no base case, or no progress towards it
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

Sum of digits, recursively

Beginner

Write a recursive function that adds up the digits of a positive whole number, so 456 gives 4 + 5 + 6 = 15.

Python
def sum_digits(n):
    if n < 10:
        return n
    return n % 10 + sum_digits(n // 10)

print(sum_digits(456))
print(sum_digits(7))
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

A single digit is the base case: it is its own sum. Otherwise n % 10 is the last digit and n // 10 is the number without it, which is a smaller problem of the same kind. For 456 the calls are 456, 45, 4; then the answers unwind as 4, 5 + 4 = 9, and 6 + 9 = 15.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

No progress towards the base case

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
def count_down(n):
    if n == 0:
        return
    print(n)
    count_down(n)
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints the same number until RecursionError: maximum recursion depth exceeded

Write this instead

def count_down(n):
    if n == 0:
        return
    print(n)
    count_down(n - 1)

Why it happens

The recursive call passes n unchanged, so it never reaches 0.

In the real world

Where this shows up in software people use every day.

  1. Printing a nested menu

    Restaurants

    A restaurant's online menu has sections inside sections. One recursive function prints it with indentation that matches the depth, however the menu is arranged.

    Why Python fits

    Each call prints one level and passes depth + 1 to the level below, so indentation follows the nesting automatically. Adding a deeper section needs no change to the code.

    Python
    def show(menu, depth=0):
        for name, item in menu.items():
            if isinstance(item, dict):
                print("  " * depth + name + ":")
                show(item, depth + 1)
            else:
                print("  " * depth + f"{name} {item:.2f}")
    
    menu = {"Drinks": {"Tea": 2.0, "Juice": {"Apple": 2.5, "Orange": 2.8}}, "Cake": 3.5}
    show(menu)
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Is recursion slower than a loop?

Usually a little, because each call has a cost, and it is limited to about 1,000 levels. For most problems in this course the difference does not matter.

Can I raise the recursion limit?

sys.setrecursionlimit() can, but it rarely fixes the real problem. Check the base case or switch to a loop first.

Do two recursive calls share their variables?

No. Every call has its own local variables, even though the names are the same.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 9 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.