← Back to course
Code Crew G5 / Week 03 / Thursday
4/6
Week 03 Β· Nesting boxes

Thursday

Down and back up
// A function that calls itself
⏱ about 15 min

Thursday: Down and back up

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."

Printing after the call

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.

StepTrays, bottom to topWhat prints
13
23, 2
33, 2, 1
43, 2, 1, 0Start
53, 2, 11
63, 22
733
What is the most trays on the stack at once for count_up(3)?
WHY THIS EXERCISECalls for 3, 2, 1 and 0 are all waiting or running at the same moment.

Both ways at once

def echo(n):
    if n == 0:
        print("bottom")
    else:
        print("down", n)
        echo(n - 1)
        print("up", n)

echo(2)
TAP THE OUTPUT LINES OF ECHO(2) INTO ORDER.
  • Tap a card.
  • Then tap its spot.
11st
22nd
33rd
44th
55th
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.?
WHY THIS EXERCISEThe deepest call finishes first, so the "up" lines come out in reverse order.

Practice lab: climb the steps

def climb(n):
    if n == 0:
        print("ground")
    else:
        climb(n - 1)
        print("step", n)

climb(3)
How many lines does climb(3) print?
What is the last line?
What is the most trays on the stack at once?
Which call prints first? Type the number inside its brackets.
TRAY CHECK
  • Read the question.
  • Tap your answer.
When climb(2) starts, does it print right away?
Which tray comes off the stack first?
What prints right after ground?
StatementTrue 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.?
WHY THIS EXERCISEWhere the print sits, before or after the call, sets the order.
How many lines does climb(6) print?
WHY THIS EXERCISECalls for 6 down to 1 each print a step, and climb(0) prints ground.

Amazing! You traced recursion going down and coming back up. Tomorrow you use it to draw a staircase of stars.

← Wednesday