Sub topic 1
Repetition with Loops
Prerequisites
This chapter assumes you can write and call functions, use for and while loops, work with basic lists, and read simple Big-O notation. All examples use Python 3.
Repetition with Loops
A loop repeats work by updating state in place. It has a starting value, a condition that decides whether to continue, and an update step. The factorial below starts result at 1 and multiplies it by each number up to n.
Recursion: Base Cases and Recursive Cases
A recursive function solves a problem by calling itself on a smaller input. It needs two parts:
- Base case: an input it answers directly, without recursing. Here that is
n == 0. - Recursive case: an input it reduces to a smaller one. Here that is
n * factorial_recursive(n - 1).
def factorial_recursive(n):
if n == 0:
return 1
return n * factorial_recursive(n - 1)
def factorial_iterative(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
print(factorial_recursive(5)) # 120
print(factorial_iterative(5)) # 120The base case plays the role of the loop's starting value. The recursive call plays the role of the update step. A common mistake is a missing or unreachable base case. For example, calling factorial_recursive(-1) never reaches 0.
What Happens on the Call Stack
Each call creates a stack frame, which holds that call's arguments, local variables, and return address. Frames are pushed onto the call stack and popped off when the call returns. A loop uses one frame no matter how many times it repeats. Recursion uses one frame per pending call.
Tracing a Recursive Call Step by Step
No multiplication happens until the base case returns. Then each frame finishes its pending work and pops off the stack.
Depth Limits and Stack Overflow
Stack memory is finite. CPython also caps recursion depth to protect the interpreter, and it raises RecursionError when a call goes past that cap.
import sys
def depth(n):
if n == 0:
return 0
return 1 + depth(n - 1)
print(sys.getrecursionlimit()) # typically 1000 in CPython
try:
depth(100_000)
except RecursionError as e:
print("RecursionError:", e)Exercise
How many stack frames are active at the deepest point of factorialrecursive(4), and how many does factorialiterative(4) need?
Show answer
factorialrecursive(4) has five active frames, for n = 4, 3, 2, 1, 0. factorialiterative(4) uses one frame for the whole computation.