Pass values in with parameters
A parameter is a name in the def's parentheses. Each call passes an argument, and the body uses it under that name, so one function works for any input.
- Define a function with one or more parameters and call it with matching arguments
- Pass arguments by position and by name (
price=4.5) - Read the TypeError for a missing argument and fix the call
The stock report in the last lesson could only report on one dictionary, the one named stock. A parameter fixes that. def print_label(product, price): says: this function needs two values, and inside the body they are called product and price.
A call supplies the arguments: print_label("Nordic Candle", 7.99). Python matches them up by position (first argument to the first parameter, and so on), then runs the body. Each call can pass different values.
Run each example to see what it prints. Running examples doesn't count toward progress.
def print_label(product, price): print(f"{product:<20}{price:>8.2f}") print_label("Nordic Candle", 7.99) print_label("Travel Yoga Mat", 24.5) print_label(price=171.99, product="Organic Speaker")
def print_label(product, price): print(f"{product:<20}{price:>8.2f}") print_label("Deluxe Vase")
A parameter can hold any value: a number, a text, a list of readings. The body uses it like any other name. Here one function prints a daily weather summary for whichever station and readings it is given, so it can be called for every station in a loop.
def print_day_summary(station, readings): high = readings[0] low = readings[0] for temp in readings: if temp > high: high = temp if temp < low: low = temp print(f"{station}: {len(readings)} readings, low {low}, high {high}") print_day_summary("Denver", [4.1, 9.8, 15.2, 11.0]) print_day_summary("Miami", [24.3, 29.1, 27.5]) for station, temps in [("Boise", [-2.5, 3.0]), ("Austin", [18.0])]: print_day_summary(station, temps)
When to use it: whenever the function's job is the same but the data changes. Mistakes to avoid:
- Passing arguments in the wrong order:
print_label(7.99, "Nordic Candle")puts the price inproduct. Pass by name when the order is easy to mix up. - Calling with too few or too many arguments.
- Reading an outer name inside the body when the value should come in as a parameter.
- Parameters are the names in the def's parentheses; arguments are the values in the call.
- Arguments match parameters by position, or by name with
name=value. - A missing or extra argument is a TypeError that names the problem.
- Next: instead of printing, hand a result back with return so the caller can use it.