Sub topic 1
What Recursion Is: Functions That Call Themselves
Prerequisites
This chapter assumes you can write and call functions, use conditionals and loops, work with basic lists, and read simple Python code.
Functions That Call Themselves
A recursive function solves a problem by calling itself on a smaller version of the same problem. Every correct recursive function has two parts. The base case returns an answer directly. The recursive case reduces the problem and calls the function again.
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120The Base Case: Knowing When to Stop
Here n == 0 is the base case. It returns 1 without making another call. If you leave out the base case, the calls never stop. Python then raises RecursionError once the chain of calls passes its depth limit.
The Recursive Case: Making the Problem Smaller
n * factorial(n - 1) is the recursive case. Each call has to move closer to the base case. A common bug is a call that never reaches it. Writing factorial(n + 1) does this, and so does calling factorial(-1), which steps past 0 and keeps going.
How the Call Stack Runs Recursive Calls
Each call gets its own stack frame, which holds that call's local variables and the point where it should resume. When factorial(3) calls factorial(2), the first frame pauses. The new frame goes on top of the stack. Frames finish in reverse order: the deepest call returns first.
Tracing a Recursive Function Step by Step
You can see the stack by printing before and after the recursive call:
def countdown(n):
if n < 0:
return
print("enter", n)
countdown(n - 1)
print("exit", n)
countdown(2)
# enter 2
# enter 1
# enter 0
# exit 0
# exit 1
# exit 2All the "enter" lines print first, while the frames are being pushed. The "exit" lines print in reverse order as each frame resumes after its deeper call returns.
Exercise
What happens when you call factorial(-1), and how would you fix it?
Show answer
The argument goes -1, -2, -3, and so on, so it never reaches the base case n == 0. Python raises RecursionError. To fix it, change the base case to n <= 0, or raise ValueError for negative input.
Exercise
What does countdown(1) print?
Show answer
enter 1, enter 0, exit 0, exit 1, with each on its own line.