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
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.
def countdown(n):
if n == 0:
print("Lift off!")
return
print(n)
countdown(n - 1)
countdown(5)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.
- def factorial(n):
- if n == 1:
- return 1
- return n * factorial(n - 1)
- answer = factorial(3)
- 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 notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
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 itPress 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
Write a recursive function that adds up the digits of a positive whole number, so 456 gives 4 + 5 + 6 = 15.
def sum_digits(n):
if n < 10:
return n
return n % 10 + sum_digits(n // 10)
print(sum_digits(456))
print(sum_digits(7))Press Run to see what it prints.Predict first
How it works(open after your guess)
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.
def count_down(n):
if n == 0:
return
print(n)
count_down(n)Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Restaurants
Printing a nested menu
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 + 1to the level below, so indentation follows the nesting automatically. Adding a deeper section needs no change to the code.Pythondef 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)OutputPress 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?
Can I raise the recursion limit?
Do two recursive calls share their variables?
Your notes
Sign in to keep private notes alongside this lesson.
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.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
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.