Orders at the till are rarely as tidy as total_price(15, 3). One customer says "sweet tea, not much sugar". Another only says "coffee with milk", with no quantity. One table orders five items at once. Your function has to accept all of them.
The order form on Mr. Darto's till counter has handled all of that for years. The "menu" box must be filled. The "quantity" box already has a 1 printed in it. And there is a "notes" box that can take any number of lines. You can fill the boxes in order from the top, or by writing each box's name. In a function, those boxes are the parameters, the way data goes in. return is the way data comes out. In this lesson you will see every way to fill the parameters, and how to send back more than one value.
Positional and keyword arguments
This function has three parameters, and it is called in three ways:
def make_order(menu, quantity=1, sugar="normal"):
return f"{quantity} {menu}, {sugar} sugar"
print(make_order("coffee with milk", 2)) # 2 coffee with milk, normal sugar
print(make_order("sweet tea", sugar="less")) # 1 sweet tea, less sugar
print(make_order(quantity=3, menu="coffee with milk")) # 3 coffee with milk, normal sugar
- A positional argument is filled in by its position in the call, like filling the form from the top. In the first call,
"coffee with milk"goes intomenu, and2goes intoquantity. - A keyword argument is filled in by name, like writing the box's name:
sugar="less". That is why the second call can skipquantity, which has a default, and the third call can swap the order. - If a parameter with a default is not filled, its default is used. A short example: with
def calc(a, b=10): return a + b,calc(5)gives15. - Positional arguments must come before keyword arguments. Python refuses
make_order(menu="coffee with milk", 2)withSyntaxError: positional argument follows keyword argument.
Returning several values
This function returns three values at once:
def summarize(prices):
return min(prices), max(prices), sum(prices)
cheapest, priciest, total = summarize([15, 5, 12])
print(cheapest, priciest, total) # 5 15 32
print(summarize([15, 5, 12])) # (5, 15, 32)
min,maxandsumare functions built into Python. They give the smallest value, the largest value, and the sum of all items.return a, b, creally returns one tuple: several values inside round brackets, such as the(5, 15, 32)that the last line prints. The Tuple & Set lesson explains tuples in full.cheapest, priciest, total = ...unpacks that tuple: each value goes into one name. The number of names must equal the number of values. Two names for three values fails withValueError: too many values to unpack (expected 2).
You can also use return early to leave a function. For example, a function that divides a bill by the number of people can start with if people == 0: return None, so that the function does not divide by zero.
*args: any number of arguments
Like the notes box on the form, this function accepts any number of prices:
def total(*prices):
print(prices)
return sum(prices)
print(total(15, 5, 12)) # (15, 5, 12) then 32
print(total()) # () then 0
- A
*in front of a parameter collects every positional argument into one tuple. Theprint(prices)inside the function shows that tuple. You can choose the parameter's name, but the usual name is*args, short for arguments. The*is the part that matters. - With no arguments the tuple is empty,
(), andsum(())is0. - If the prices are in one list,
total([15, 5])sends that list as one argument. The tuple then holds one list, andsumfails:TypeError: unsupported operand type(s) for +: 'int' and 'list'. Unpack the list with*in the call:total(*price_list)if the list is calledprice_list.
**kwargs: any number of keywords
A ** in front of a parameter collects every keyword argument that has no parameter of its own into one dict. A dict holds name: value pairs between curly braces (the Dictionary lesson explains it). The usual name is **kwargs, short for keyword arguments.
The same call, record("coffee with milk", "sweet tea", table=4), can be accepted or refused. It depends on the parameters in the def:
def |
Result |
|---|---|
def record(menu1, menu2): |
TypeError: record() got an unexpected keyword argument 'table' |
def record(*menu): |
TypeError: record() got an unexpected keyword argument 'table' |
def record(**info): |
TypeError: record() takes 0 positional arguments but 2 were given |
def record(*menu, **info): |
menu becomes ('coffee with milk', 'sweet tea'), info becomes {'table': 4} |
*menuholds the positional arguments,**infoholds the keyword arguments. The first twodeflines have no place fortable=4, and the third has no place for the two menu items. Only thedefin the last row has a place for both.- Another example:
def info(*args, **kwargs): print(len(args), len(kwargs)), theninfo(1, 2, 3, x=10, y=20). It prints3 2: three positional, two keyword.len()counts the items. - One more example:
def f(a, b, *args, **kwargs)accepts the callf(1, 2, x=3). The result isa=1,b=2, an emptyargs, andkwargsholding{'x': 3}.
A list as a default
This function uses an empty list as a default. Look at what the second call prints:
def add_to_order(item, order=[]):
order.append(item)
return order
print(add_to_order("coffee with milk")) # ['coffee with milk']
print(add_to_order("sweet tea")) # ['coffee with milk', 'sweet tea']
.append(item) adds item to the end of the list. A default value is made once, when the def line runs, not each time the function is called. So every call without a second argument uses the same list, and its items pile up: each call adds one more. The second call prints ['coffee with milk', 'sweet tea'], even though only "sweet tea" was sent.
The fix: use None as the default, then make a new list inside the function.
def add_to_order(item, order=None):
if order is None:
order = []
order.append(item)
return order
Now add_to_order("coffee with milk") gives ['coffee with milk'], and add_to_order("sweet tea") gives ['sweet tea']. is None checks whether the value really is None.
📌 Keyword-only parameters and parameter order
Parameters written after a * (or after *args) can only be filled by name. They are called keyword-only parameters:
def record(menu1, menu2, *, table):
print(menu1, menu2, table)
record("coffee with milk", "sweet tea", table=4) # coffee with milk sweet tea 4
record("coffee with milk", "sweet tea", 4) # TypeError: record() takes 2 positional arguments but 3 were given
This is useful because a number with an unclear meaning (is 4 the table or the quantity?) must be named.
The official order of parameters:
- ordinary parameters,
*args,- keyword-only parameters (they may have defaults),
**kwargs.
In a call, * and ** work the other way. add_up(*[1, 2, 3]) unpacks a list into three positional arguments, the same as add_up(1, 2, 3). add_up(**{"a": 10, "b": 20, "c": 30}) unpacks a dict into keyword arguments, the same as add_up(a=10, b=20, c=30).
⚠️ Defaults that pile up and arguments in the wrong place
- A list or dict as a default.
order=[]is shared by every call. Useorder=None, then make a new list inside the function. - Positional after keyword.
make_order(menu="coffee with milk", 2)givesSyntaxError: positional argument follows keyword argument. - One parameter filled twice.
make_order("coffee with milk", menu="sweet tea")fillsmenuby position, then once more by name. The result isTypeError: make_order() got multiple values for argument 'menu'. - The wrong number of names when unpacking.
cheapest, priciest = summarize(...)for three values givesValueError: too many values to unpack (expected 2).
TL;DR: Positional arguments are filled in by order, keyword arguments by name (sugar="less"), and positional arguments always come before keyword arguments. A default is used when its argument is not sent (calc(5) with the default b=10 adds the two, which gives 15). return a, b, c returns a tuple (several values in one pair of brackets) that can be unpacked into several names at once. *args collects the leftover positional arguments into a tuple. **kwargs collects the leftover keyword arguments into a dict (pairs of a name and a value). So def f(a, b, *args, **kwargs) accepts f(1, 2, x=3). Parameters after * can only be filled by name. Never use a list as a default: it is made once and shared by every call. Use None.
⚡ Fill in by order, or by name
Write:
def make_order(menu, quantity=1, sugar="normal"):
return f"{quantity} {menu}, {sugar} sugar"
print(make_order("coffee with milk", 2)) # 2 coffee with milk, normal sugar
print(make_order("sweet tea", sugar="less")) # 1 sweet tea, less sugar
Meaning: In the first call, "coffee with milk" and 2 are filled in by order, into menu and then quantity. Each one is a positional argument. In the second call, sugar="less" is a keyword argument: it is filled in by name, so quantity, which has a default, can be skipped. Positional arguments always come before keyword arguments.
⚡ Several values at once
Write:
def summarize(prices):
return min(prices), max(prices), sum(prices)
cheapest, priciest, total = summarize([15, 5, 12])
print(cheapest, priciest, total) # 5 15 32
Meaning: min, max and sum give the smallest value, the largest value and the sum. return a, b, c returns one tuple (several values in one pair of brackets), and the next line unpacks it into three names at once. The number of names must equal the number of values.
⚡ Collecting the leftover arguments
Guess first: the * makes menu collect any number of positional arguments. Does def record(*menu): accept record("coffee with milk", "sweet tea", table=4)?
No: TypeError: record() got an unexpected keyword argument 'table'. *menu only collects the positional arguments, and table=4 is a keyword argument.
Meaning: A parameter with *, usually *args, collects the leftover positional arguments into a tuple. A parameter with **, usually **kwargs, collects the leftover keyword arguments into a dict (pairs of a name and a value). So def f(a, b, *args, **kwargs) accepts f(1, 2, x=3): a=1, b=2, args is empty and kwargs holds {'x': 3}.
⚡ A list default that piles up
Write:
def add_to_order(item, order=[]):
order.append(item)
return order
print(add_to_order("coffee with milk"))
print(add_to_order("sweet tea"))
Guess first: .append(item) adds item to the end of the list. What does the second print print?
['coffee with milk', 'sweet tea'], even though only "sweet tea" was sent.
Meaning: A default value is made once, when def runs, so every call shares the same list. Use order=None, then make a new list inside the function.