← Back to course
Code Crew G5 / Week 02 / Tuesday
2/6
Week 02 Β· Functions call functions

Tuesday

The caller waits
// Who waits, who returns
⏱ about 15 min

Tuesday: The caller waits

It is probe launch time. Rocket presses the big button, but the launch pauses.

"Why did it stop?" Rocket asks. "I said launch!"

Raven points at the screen. "What do you notice? Your launch function asked for a scanner check first."

A message pops up: scanner ready. Then the launch finishes.

Nova hovers beside the screen. "Here is a hint. Watch the order of the messages. Who was waiting?"

Follow the messages

When a function calls a helper, the caller stops on that line. The helper runs all the way through.

Then the caller picks up again on its next line. Print messages show the order clearly.

def check_scanner():
    print("Raven: scanner ready")

def launch_probe():
    print("Rocket: starting launch")
    check_scanner()
    print("Rocket: probe away")

launch_probe()
Output:
Rocket: starting launch
Raven: scanner ready
Rocket: probe away

Defining a function does not run it. Only the last line starts anything. That line calls launch_probe.

Three levels deep

Now the scanner check calls its own helper. Read it carefully before you answer.

def check_lens():
    print("lens clean")

def check_scanner():
    print("scanner start")
    check_lens()
    print("scanner done")

def launch_probe():
    print("launch start")
    check_scanner()
    print("launch done")

launch_probe()
TAP THE OUTPUT LINES INTO THE ORDER THEY PRINT.
  • Tap a card.
  • Then tap its spot.
11st
22nd
33rd
44th
55th
Statement about the program aboveTrue or false?
launch_probe keeps printing while check_scanner runs.?
check_lens finishes before check_scanner finishes.?
"launch done" is the last line printed.?
check_lens runs first because it is written first.?
WHY THIS EXERCISEEach caller waits for its helper, so the deepest helper finishes first.

Practice lab: beep, beep, go

def beep():
    print("beep")

def warm_up():
    print("warm up")
    beep()
    beep()

def launch():
    warm_up()
    print("go")

launch()
print("end")
How many lines print in all?
What is the first line?
What prints right after the second beep?
How many times is beep called?
WHO WAITS?
  • Read the question.
  • Tap your answer.
While beep runs, which functions are waiting?
Which call starts everything?
What prints right after go?
StatementTrue or false?
beep prints before warm up.?
go prints after both beeps.?
end prints last.?
warm_up runs twice.?
WHY THIS EXERCISETracing calls in order is how you predict any output.
Suppose launch calls warm_up two times before go. How many beeps print?
WHY THIS EXERCISE2 calls times 2 beeps makes 4 beeps.

Super tracing! You followed three functions at once. Tomorrow we picture this waiting as a stack of trays.

← Monday