A function that calls itself
factorial(n) is n × (n−1) × … × 1. The recursive definition is: if n is 0, answer 1; otherwise answer n × factorial(n − 1).
Every call gets its own frame on the call stack with its own n. Deeper calls push new frames. When a call returns, its frame pops and the value goes back to the caller.
n == 0) stops the chain. Without it, the stack would grow forever.def factorial(n): if n == 0: return 1 return n * factorial(n - 1)
Try factorial(3) first — four frames is enough to see the pattern.
Run the simulation
Frames grow downward in time but upward on screen — the top frame is the one running now.
How recursion uses the stack
Same LIFO idea as a data-structure stack — but the runtime manages it for you.
Each call adds a frame
Locals like n live in that frame. Deeper calls sit above older ones.
Base case stops growth
n == 0 → return 1 is the turnaround. Then values climb back up.
Return unwinds the stack
A finished frame pops and hands its value to the caller waiting below.