1.2.37Introduction to Programming (Python)

Recursion — call stack visualization, base case, recursive case

2,008 words9 min readdifficulty · medium6 backlinks

WHAT is recursion?


HOW the call stack works

Figure — Recursion — call stack visualization, base case, recursive case

DERIVATION — building factorial from scratch

We want n!=123nn! = 1 \cdot 2 \cdot 3 \cdots n.

Step 1 — Spot self-similarity. Notice n!=n(n1)!n! = n \cdot (n-1)!. Why this step? Because the product of 1..n1..n is just nn times the product of 1..(n1)1..(n-1) — the same kind of problem, one size smaller. That self-reference is the recursive case.

Step 2 — Find where shrinking stops. (n1)!(n-1)! leads to (n2)!(n-2)! ... down to 0!0!. By definition 0!=10! = 1. Why this step? We need an input we can answer with no further recursion. 0!=10! = 1 needs no multiplication, so it's the base case.

Step 3 — Combine into a function.

def fact(n):
    if n == 0:          # base case
        return 1
    return n * fact(n-1)  # recursive case

Common mistakes (Steel-manned)


Recursion vs Iteration (80/20)


Recall Feynman: explain to a 12-year-old

Imagine you're standing in a long line and want to know your position. You can't see the front, so you tap the person ahead and ask "what's your number?" They do the same thing, tapping the next person, and so on — until the very first person says "I'm number 1!" (that's the base case — they answer without asking anyone). Then the answer travels back: each person adds 1 to what they heard and tells the person behind. That's recursion: ask a smaller copy of yourself, wait, then add your bit. The "people waiting for answers" are the call stack.


Active-recall flashcards

What two parts must every recursive function have?
A base case (stops recursion) and a recursive case (calls itself on a smaller input).
What is the base case?
The smallest input whose answer is known directly, with no further recursive call — it stops the recursion.
Why does a missing/wrong base case crash?
Recursion never stops, frames pile up, and Python hits maximum recursion depth → RecursionError (stack overflow).
What data structure stores active function calls, and what order does it follow?
The call stack, which is LIFO (last-in-first-out).
In fact(3), which call returns its value FIRST?
fact(0) — the base case — because the deepest/last-pushed frame finishes first (LIFO).
What are the two phases of a recursive run?
Winding (pushing frames going down) and unwinding (popping frames and combining returns going back up).
Why must the recursive call use n-1 (or L[1:])?
To make progress toward the base case; otherwise the problem never shrinks and recursion is infinite.
What happens if you forget return in the recursive case?
The sub-call's result is discarded; the function returns None instead of the computed value.
Do all recursive calls share the same local variable n?
No — each stack frame has its own independent copy of the locals.
Self-similar definition of factorial used to derive recursion?
n! = n · (n-1)! with 0! = 1.

Connections

Concept Map

has

has

calls self on

shrinks toward

stops

missing base case gives

raises

runs on

Winding pushes

Unwinding pops on

example

recursive case

base case

Recursion

Base case

Recursive case

Smaller input

Infinite recursion

RecursionError stack overflow

Call stack LIFO

Stack frames

factorial n

n * fact(n-1)

fact(0) = 1

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Recursion ka matlab hai ek function jo khud ko hi call karta hai — lekin har baar thode chote problem ke saath. Socho jaise factorial: n!=n×(n1)!n! = n \times (n-1)!. Yahan bada answer chote answer pe depend karta hai, isiliye function khud ko n-1 ke saath call karta hai. Do cheezein hamesha chahiye: base case (jahan answer seedha pata hai, jaise 0!=10! = 1, aur recursion ruk jaata hai) aur recursive case (jahan function chote input ke saath khud ko bulata hai). Base case bhool gaye to recursion kabhi rukega nahi → RecursionError (stack overflow).

Call stack ko aise samjho: jab fact(3) chalta hai, woh fact(2) ka answer maangta hai, isliye pause ho jaata hai aur memory mein ek "frame" ban jaata hai. Phir fact(2), fact(1), fact(0) — frames ek ke upar ek pile-up hote jaate hain. Isko winding kehte hain. Jab base case (fact(0)=1) hit hota hai, tab return values neeche se upar travel karte hain: 11261 \to 1 \to 2 \to 6. Yeh unwinding hai. Stack LIFO hota hai — sabse last call sabse pehle khatam hoti hai.

Sabse common galti: log sochte hain "input chota ho raha hai to apne aap ruk jayega" — nahi! Jab tak tum explicitly if n == 0: return nahi likhoge, rukega nahi. Doosri galti: recursive call mein return lagana bhool jaana — phir answer waapas hi nahi aata, None mil jaata hai. Yaad rakho B.A.S.E.: Base case pehle, Always shrink karo, Save (return + combine) the result, aur Each call ka apna alag frame hota hai. Yeh idea aage Fibonacci, tree traversal, aur dynamic programming mein bahut kaam aayega.

Go deeper — visual, from zero

Test yourself — Introduction to Programming (Python)

Connections