Define a function and call it
def gives a block of code a name. Nothing in the block runs until the name is called, and each call runs the whole block again.
- Write a function with
def name():and an indented body - Explain that defining a function runs nothing, and calling it runs the body from the top
- Recognise the two first mistakes: calling before the def, and forgetting the parentheses
Programs repeat themselves. A shop prints the same opening hours at the top of a page and again at the bottom of an email; a stock report runs in the morning and again after a delivery. Copying the lines works until something changes, and then every copy has to be fixed.
A function gives a block of code a name. def show_hours(): starts it; the indented lines under it are its body. Defining the function runs nothing. Writing show_hours(), the name with parentheses, is a call: the body runs from the top, then the program carries on after the call.
Run each example to see what it prints. Running examples doesn't count toward progress.
def show_hours(): print("Mon-Fri 09:00-18:00") print("Sat 10:00-16:00") print("Sun closed") print("Runtime Market, opening hours") show_hours() print() print("Your order has shipped. Visit us:") show_hours()
print("Opening hours:") show_hours() def show_hours(): print("Mon-Fri 09:00-18:00")
A function's body can hold anything you have learned: loops, if, dictionaries. It can also read names defined at the top of the program. It reads their values at the moment it is called, not when it was defined, so the same call can report something different later in the program.
stock = {"P0607": 2, "P0208": 14, "P0659": 0}
def report_low_stock():
for product_id, units in stock.items():
if units < 3:
print("low:", product_id, units)
print("end of report")
report_low_stock()
stock["P0659"] = 20
report_low_stock()When to use it: whenever the same steps are needed in more than one place, or when a block does one job you can name (report_low_stock says what the lines do). Mistakes to avoid:
- Calling a function above its
def. - Forgetting the parentheses:
show_hourson its own line names the function but doesn't call it, so nothing happens. - Indenting the call under the
def, which makes the call part of the body.
def name():plus an indented body defines a function; nothing in the body runs yet.name()runs the whole body from the top, as often as you call it, after the def.- A function that reads an outer name sees its value at the moment of the call.
- Next: parameters, so the data comes in through the call instead of from outside names.