Recursion happens when a solution asks a smaller version of itself for help. It is like opening a box and finding a smaller box inside.
The smaller box may hold another smaller box. But this cannot continue forever. At some point, we need a final tiny box with no box inside.
The stopping rule
The rule that stops recursion is called the base case. Without a base case, the computer keeps opening boxes until it runs out of room.
A countdown is a simple example. To count down from 3, say 3 and ask for a countdown from 2. That says 2 and asks for 1. That says 1 and asks for 0. At 0, we stop.
- If the number is 0, say done. This is the base case.
- Otherwise, say the number.
- Ask the same countdown to handle one smaller number.
Big problems become small problems
Suppose you want to count every toy in nested boxes. Count the toys in the first box. If you find another box, use the same counting rule inside it. Each call handles one small place.
Recursion feels natural for folders inside folders, branches inside trees, and paths that split into more paths.
Recursion has a cost
The computer must remember every unfinished call. Too many calls can fill its memory. Sometimes a loop is simpler. Recursion is a tool, not a rule that must be used everywhere.
def countdown(number):
if number == 0: # Base case: stop here
print("Done!")
return
print(number)
countdown(number - 1)
countdown(3)Your tiny challenge
Explain how to climb down five stairs using recursion: step down once, then solve the same problem with one fewer stair. What is the base case? It is when no stairs are left.
