Functions: reusable steps
A function is a set of steps with a name. You write the steps once with def, then run them whenever you need them by calling the name. Step through a two-line function, area(w, h), called twice, and watch where Python goes: into the function, back out with an answer, and what happens to its local variables along the way.
5 quick questions
Pick an answer to see why. Your score saves with your progress.
01What happens when Python runs the line def area(w, h): and its indented body?
def only creates the function and gives it a name. The body runs later, each time something calls area(...).
02In a = area(3, 4) , what are 3 and 4?
The values you pass in a call are arguments. The names in the def line that receive them, w and h, are parameters.
03After return w * h runs inside area(5, 2), where does the program carry on?
return ends the call and sends its value back to where the call was made. That line then carries on, for example storing 10 in b.
04After a = area(3, 4) has finished, what does print(w) outside the function do?
w is a local variable of area. It exists only while the call is running, so outside the function the name w does not exist.
05What does a function that has no return statement send back?
Without return, a function still ends and goes back to its caller, but the value it sends back is None.
Glossary
- Function
- A named set of steps you can run whenever you need them, such as area.
- def
- The Python keyword that defines a function: def area(w, h): followed by an indented body.
- Parameter
- A name in the def line, such as w or h, that receives a value when the function is called.
- Argument
- A value passed in a call, such as 3 and 4 in area(3, 4).
- Call
- Running a function by writing its name with brackets, such as area(3, 4). Python jumps into the function, then comes back.
- return
- The statement that ends a call and sends a value back to the line that made the call.
- Local variable
- A name that exists only inside one call of a function, such as w and h. It is gone when the call returns.
- Call frame
- The working space Python makes for one call, holding its local variables. It is cleared when the call ends.
Notes and sources
- 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.
- def is itself a statement that runs: it builds a function object and binds the name area to it. The body runs only when the function is called.
- A function that ends without a return statement sends back the special value None.
- Here arguments are matched to parameters by position. They can also be passed by name, as in area(h=4, w=3).
- print is a built-in function: Python defines it for you, and it returns None after writing its text out.
Quiz Unlocks after the last step.