Rocket moves one line in his countdown program. Now the screen shows Start, then 1, 2, 3.
"It counts up now!" he says. "But I only moved one print line. How?"
Raven stacks four trays on the table. "What do you notice about when each call can print?"
"Oh. Each call has to wait for the call it made," Rocket says slowly.
Nova taps the top tray. "Here is a hint. Think about which tray comes off first."
def count_up(n):
if n == 0:
print("Start")
else:
count_up(n - 1)
print(n)
count_up(3) Output: Start 1 2 3
Now each call makes its smaller call first. Its own print waits until that call returns.
The calls stack up like trays: count_up(3), then (2), then (1), then (0) on top.
count_up(0) prints Start and returns. Then count_up(1) can finish and print 1, and so on back down the stack.
| Step | Trays, bottom to top | What prints |
|---|---|---|
| 1 | 3 | |
| 2 | 3, 2 | |
| 3 | 3, 2, 1 | |
| 4 | 3, 2, 1, 0 | Start |
| 5 | 3, 2, 1 | 1 |
| 6 | 3, 2 | 2 |
| 7 | 3 | 3 |
def echo(n):
if n == 0:
print("bottom")
else:
print("down", n)
echo(n - 1)
print("up", n)
echo(2) | Statement about echo(2) | True or false? |
|---|---|
| "down" lines print on the way to the stopping point. | ? |
| "up 2" prints before "up 1". | ? |
| echo(0) is the call on top of the stack. | ? |
def climb(n):
if n == 0:
print("ground")
else:
climb(n - 1)
print("step", n)
climb(3) | Statement | True or false? |
|---|---|
| climb(3) prints step 3 last. | ? |
| climb(3) prints step 1 before ground. | ? |
| climb(2) waits for climb(1) to return. | ? |
| Moving the print above the call would flip the order of the step lines. | ? |
Amazing! You traced recursion going down and coming back up. Tomorrow you use it to draw a staircase of stars.