1def average(nums):2 total = sum(nums)3 return total / len(nums) total / len(nums)45a = average([8, 6, 10])6b = average([4, 5])7print(a, b)function[8, 6, 10]248.08.0[4, 5]4.58.0 4.5
Code card: avg.py; the highlighted line is the one runningCall frame: scratch space for one call (nums, total)Terminal: where print() writesMemory boxes: the global names average, a and bdef average(nums): stores a function under the name average; its indented body runs only when the function is called. Each call makes a fresh call frame, the tray at the back, where the parameter nums names the argument and the body's local name total lives. return sends one value back to the calling line and the frame is cleared away. Two calls reuse the same two lines and give two answers, 8.0 4.5. In the last step the word return is struck out: the function then sends back None.

Define

  1. A function is a named group of steps you can run whenever you need them. def average(nums): makes one and stores it under the name average. The indented lines 2 and 3 are its body: they do not run yet.

First call

Second call

Use and pitfalls

Try it yourself

;; step 1/9 · line 1: def average(nums):
>>> def average(nums):
...     total = sum(nums)
...     return total / len(nums)
...
>>> average           # just the name: nothing runs
<function average at 0x…>

The tray is a call frame: each call gets a fresh table for its local names (here nums and total). When the call returns, the frame is released and those names can no longer be reached from outside. The / operator always gives a float, even when the division is exact: 24 / 3 is 8.0, not 8. Use // for whole-number (floor) division.