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

Wednesday

A stack of trays
// Who waits, who returns
⏱ about 15 min

Wednesday: A stack of trays

The fleet galley has a tall stack of lunch trays. Rocket grabs one from the bottom, and the whole pile wobbles.

"Whoa! Steady!" he laughs. He slides it back.

Raven takes a tray from the top instead. "What do you notice about how a stack works?"

"You add to the top, and you take from the top," Rocket says.

Nova projects a tray with a function name on it. "Here is a hint. Python keeps its calls in a stack just like this."

The call stack

Python keeps track of running functions in a call stack. Picture each call as a tray with the function name on it.

When a function is called, a new tray goes on top. When it returns, its tray comes off the top.

The function on the top tray is the one running right now. Every tray below it is waiting.

Moment in the launch programTrays, bottom to top
launch_probe() is calledlaunch_probe
launch_probe calls check_scannerlaunch_probe, check_scanner
check_scanner calls check_lenslaunch_probe, check_scanner, check_lens
check_lens returnslaunch_probe, check_scanner
check_scanner returnslaunch_probe
launch_probe returns(empty)

The stack grows as calls go deeper. It shrinks as each function returns. The last tray on is the first tray off.

USE THE TABLE ABOUT THE LAUNCH PROGRAM.
  • Read the question.
  • Tap your answer.
While "lens clean" prints, which tray is on top?
What is the most trays on the stack at once?
Which tray comes off first?
def d():
    print("d")

def c():
    d()

def b():
    c()

def a():
    b()

a()
When d prints, how many trays are on the call stack?
WHY THIS EXERCISENo function has returned yet, so every call is still a tray on the stack.
Try it
Stack four books. Write a function name on a sticky note for each one.
Take them off one at a time and say "returns" each time.

Practice lab: watch the trays

def c():
    print("c runs")

def b():
    print("b starts")
    c()
    print("b ends")

def a():
    b()
    c()

a()
How many lines print?
What is the most trays on the stack at once?
How many trays are there when the second c runs?
How many times is c called?
TRAY CHECK
  • Read the question.
  • Tap your answer.
When b ends prints, which tray is on top?
Which tray stays at the bottom the whole time?
Right after the second c returns, what is on the stack?
StatementTrue or false?
A new call puts a tray on top.?
A return takes a tray from the bottom.?
The function on top is the one running.?
The same function can be on the stack at two different times.?
WHY THIS EXERCISETrays go on and come off the top, every time.
f calls g, g calls h, and h calls k. When k runs, how many trays are on the stack?
WHY THIS EXERCISEf, g, h and k are all on the stack.

Nice work! The call stack is how Python remembers where to go back to. Tomorrow we follow the values that come back.

← Tuesday