Step 1 — Spot self-similarity.
Notice n!=n⋅(n−1)!.
Why this step? Because the product of 1..n is just n times the product of 1..(n−1) — the same kind of problem, one size smaller. That self-reference is the recursive case.
Step 2 — Find where shrinking stops.(n−1)! leads to (n−2)! ... down to 0!. By definition 0!=1.
Why this step? We need an input we can answer with no further recursion. 0!=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
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.
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×(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!=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: 1→1→2→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.