Recursive factorial

Each call to factorial(n) waits for a smaller call. Watch frames pile onto the call stack, hit the base case, then unwind with return values.

Programming Beginner Recursion · Call stack ~8 min
The idea

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.

TipThe base case (n == 0) stops the chain. Without it, the stack would grow forever.
IdeaDefinition
factorial.pyPython
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.

Interactive

Run the simulation

Frames grow downward in time but upward on screen — the top frame is the one running now.

Step 0 / 0
factorial.pyPython
Call stackfactorial(3)
Ready
Shortcuts: Space play/pause · → step · ← back · R reset
Remember

How recursion uses the stack

Same LIFO idea as a data-structure stack — but the runtime manages it for you.

Push

Each call adds a frame

Locals like n live in that frame. Deeper calls sit above older ones.

Base

Base case stops growth

n == 0 → return 1 is the turnaround. Then values climb back up.

Pop

Return unwinds the stack

A finished frame pops and hands its value to the caller waiting below.