1def area(w, h):2 return w * h34a = area(3, 4)5b = area(5, 2)6print(a + b)wh
Code card: the program; highlighted lines are the ones the step is aboutMemory boxes: the global names area, a and bCall frame: appears for each call, holds the local variables w and h, then is clearedScreen: where print shows its outputEach step lights the lines it is about. A call lights the calling line and the def line, and a token carries the arguments up into the function while a call frame tray appears with the local variables w and h. A return carries the answer back down to the line that called, and the tray is cleared away. The same two lines of area run for both calls, with different arguments, and give 12 and 10; print(a + b) shows 22. The drawing shows each call’s local variables on a tray, the call frame. In CPython every call gets its own frame object; when the call returns, the frame is released and its local names can no longer be reached.

Define

  1. def creates a function: a named list of steps. Python stores it under the name area, for later. The indented line does not run yet. w and h are parameters: names for values a caller will hand in.

First call

Second call

Why functions

Try it in the Python prompt

;; step 1/10 · line 1: def area(w, h):
>>> def area(w, h):
...     return w * h
...
>>> area
<function area at 0x…>

The drawing shows each call’s local variables on a tray, the call frame. In CPython every call gets its own frame object; when the call returns, the frame is released and its local names can no longer be reached. A function that ends without a return statement sends back the special value None.