Parameters & Return Values — Python

Positional arguments are filled in by order, keyword arguments by name (sugar="less"), and positional arguments always come before keyword arguments. A…

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

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)

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

**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}

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:

  1. ordinary parameters,
  2. *args,
  3. keyword-only parameters (they may have defaults),
  4. **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

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.

What you will learn