Python Function Calls and the Stack—Lesson 1

1def foo():
2 print("foo line 1")
3 print("foo line 2")
4 print("foo line 3")
6def fum():
7 print("fum line 1")
8 print("fum line 2")
9 print("fum line 3")
11def bar():
12 print("bar line 1")
13 fum() # bar line 2
14 foo() # bar line 3
15 print("bar line 4")
17def go():
18 bar() # go line 1
20go() ####
—end of file—

Press the ⍄ key above to move forward through the program, and the ⍃ key to move back.

Consider the code in the table at left.

What will be printed?

To know, we have to know how Python decides
the order in which to run lines of code:

In this lesson we are concentrating only on function calls,
and returning from function calls.

A function call works like this:

Returning from a function works like this:

Note that when you "fall off the end of a function"—which happens, for example, at lines 5,10,16,19— that automatically returns from that function as if a return statement appeared there.

Clicking on the arrows at the bottom of the code (⍃,⍄) allow you to step through the code one line at a time and see the order in which the program is executed. The red arrow () indicates the next line of code to be executed. Click through the lines of code until you understand how Python chooses which line to execute next.

You may be wondering—how does Python know "where to go back to" when it returns from a function? That is, we know Python should "pick up where it left off"—but how does it remember where it left off?

The answer has to do with something called the run time stack, and that is what we'll explore in lesson 2.