Comet bursts into the maker space with her sketch notebook open. "New idea for the launch countdown," she says. "The function prints a number, then calls itself with one less."
Wren looks up from his clipboard. "A function that calls itself? What does the evidence say? When does it ever stop?"
"When it reaches zero," Comet says. "Then it prints Go! instead."
Nova hovers over the bench and projects a staircase of glowing cards, each one a little smaller. "How can I help?" she asks. "Each card is one call. Watch which card stops the climb."
Comet grins and turns to you. "Lead programmer, trace it before we run it."
A recursive function is a function that calls itself.
It needs at least one base case, which stops the recursion. It also needs at least one recursive call.
Recursion is another way to repeat, like a loop. Each call works on a smaller problem until the base case is reached.
# countdown.py
def countdown(n):
if n == 0:
print("Go!")
else:
print(n)
countdown(n - 1)
countdown(3) Predict the output of countdown(3) before you look. Then compare with the run:
3 2 1 Go!
Here is what the misspelled call gives. The first call printed 3 before it reached the bad line:
# countdown.py (with a typo)
def countdown(n):
if n == 0:
print("Go!")
else:
print(n)
countdwn(n - 1)
countdown(3) 3
Traceback (most recent call last):
File "countdown.py", line 10, in <module>
countdown(3)
~~~~~~~~~^^^
File "countdown.py", line 7, in countdown
countdwn(n - 1)
^^^^^^^^
NameError: name 'countdwn' is not defined. Did you mean: 'countdown'? A call does not finish until the call it made has finished. So work written after the recursive call happens on the way back.
Trace echo(3) on paper first. Write each line it prints, in order.
# echo.py
def echo(n):
if n == 0:
print("base case")
else:
print("going down", n)
echo(n - 1)
print("coming back", n)
echo(3) going down 3 going down 2 going down 1 base case coming back 1 coming back 2 coming back 3
| Statement | True or false? |
|---|---|
| A recursive function calls itself. | ? |
| A recursive function with no base case stops on its own. | ? |
| echo(1) prints coming back 1 before base case. | ? |
| Each recursive call should work on a smaller problem. | ? |
You traced your first recursive function, lead programmer. Tomorrow you will stack the calls up and watch the answers come back.