Intermediate Python · Lesson 1 of 14

Functions in depth

Use default values safely, collect any number of arguments with *args and **kwargs, and force clear calls with keyword-only parameters.

About 18 minutes · code runs in your browser, nothing to install

In Functions: write your own commands you wrote functions with parameters, return and default values. This lesson looks at the extra tools def (functions) gives you: functions that take any number of arguments, parameters that must be named, and one famous trap with default values.

Positional and keyword arguments

A positional argument is matched by its place in the call. A keyword argument is matched by its name (nights=3). You can mix them, but positional ones always come first.

Pythoneditable
def book_room(city, nights, guests=1):
    return f"{city}: {nights} nights for {guests} guest(s)"

print(book_room("Lisbon", 3))
print(book_room("Lisbon", 3, 2))
print(book_room(nights=2, city="Vienna"))
print(book_room("Rome", nights=4, guests=3))
Output
Lisbon: 3 nights for 1 guest(s)
Lisbon: 3 nights for 2 guest(s)
Vienna: 2 nights for 1 guest(s)
Rome: 4 nights for 3 guest(s)

The mutable default trap

A default value is created once, when Python reads the def line, not each time the function runs. For numbers and strings that does not matter. For a list or a dictionary it does: every call that uses the default shares the same list.

Pythoneditable
def add_item(item, basket=[]):
    basket.append(item)
    return basket

print(add_item("bread"))
print(add_item("milk"))

def add_item_safe(item, basket=None):
    if basket is None:
        basket = []
    basket.append(item)
    return basket

print(add_item_safe("bread"))
print(add_item_safe("milk"))
Output
['bread']
['bread', 'milk']
['bread']
['milk']

The first version remembers bread from the earlier call. The safe version uses None as the default and creates a new list inside the function: the habit to keep for any list, dictionary or set.

Any number of arguments: *args

A parameter written with a star, like *prices, collects all the extra positional arguments into a tuple. The name args is only a habit; any name works.

Pythoneditable
def total(*prices):
    print("Got:", prices)
    return sum(prices)

print(total(2.5, 4, 1.5))
print(total())
Output
Got: (2.5, 4, 1.5)
8.0
Got: ()
0

Any number of named arguments: **kwargs

Two stars, like **details, collect the extra keyword arguments into a dictionary: each name becomes a key and each value its value.

Pythoneditable
def make_profile(name, **details):
    print("Name:", name)
    for key, value in details.items():
        print(f"  {key}: {value}")

make_profile("Amara", city="Nairobi", age=29)
make_profile("Lars")
Output
Name: Amara
  city: Nairobi
  age: 29
Name: Lars

Keyword-only parameters

Every parameter written after * (or after *args) is keyword-only: the caller must write its name. This keeps calls readable when a function has options that are easy to mix up. The full order of parameters is: normal ones, *args, keyword-only ones, then **kwargs.

Pythoneditable
def transfer(amount, *, currency="EUR", note=""):
    return f"Sending {amount} {currency} {note}".strip()

print(transfer(50))
print(transfer(50, currency="USD", note="for lunch"))

try:
    transfer(50, "USD")
except TypeError:
    print("Error: currency must be given by name")
Output
Sending 50 EUR
Sending 50 USD for lunch
Error: currency must be given by name

✎ Exercise

Write average(*numbers, decimals=1) that returns the average of any number of values, rounded to decimals places. With no numbers it should return 0.

Hint: numbers is a tuple, so sum(numbers) and len(numbers) work on it. An empty tuple counts as False.

Your codewrite your answer, then Run
def average(*numbers, decimals=1):
    # your code here
    return 0

print(average(4, 5, 6))
print(average(1, 2, 2, decimals=2))
print(average())

Expected output:

5.0
1.67
0
Show a solution
Solutioneditable
def average(*numbers, decimals=1):
    if not numbers:
        return 0
    return round(sum(numbers) / len(numbers), decimals)

print(average(4, 5, 6))
print(average(1, 2, 2, decimals=2))
print(average())
Output
5.0
1.67
0

Check yourself

1. Inside def f(*args), what kind of value is args?

2. With def f(a, *, b), which call works?

3. Why is def f(items=[]) risky?

Spotted a mistake on this page? Tell us