Simple Recursion: Countdown
You'll learn how to implement your first recursive function by counting down from a number to zero, visualizing how recursive calls build up and then resolve.
The Core Idea
A countdown function perfectly demonstrates recursion in action. When you call countdown(3), it prints 3, then calls countdown(2), which prints 2, then calls countdown(1), which prints 1, then calls countdown(0). At zero (the base case), the function stops calling itself and returns. Each call then finishes in reverse order, unwinding the "stack" of paused function calls.
Think of it like a tower of boxes: you stack them up one by one (3, 2, 1, 0), and once you place the last box (base case), you're done stacking and can walk away.
Example Implementation
def countdown(n):
if n == 0: # Base case
print("Blastoff!")
return
print(n) # Do something before recursive call
countdown(n - 1) # Recursive case
When you run countdown(3):
- Prints
3, callscountdown(2)- Prints
2, callscountdown(1)- Prints
1, callscountdown(0)- Prints
"Blastoff!", returns
- Prints
- Returns to
countdown(1)
- Prints
- Returns to
countdown(2)
- Prints
- Returns to
countdown(3)
Each call waits for the next one to finish before it can complete and return.
Why This Matters
This simple pattern shows how recursion stacks up (each call pauses) and unwinds (each call completes). You're seeing the anatomy of a recursive call in its simplest form: a clear base case (n == 0) and a recursive case that moves toward it (n - 1).
Key Takeaway: A countdown function demonstrates how recursive calls pile up until the base case is reached, then unwind in reverse order—showing the fundamental "stack and unwind" nature of recursion.