Arguments can be passed by name as well as by position. These are keyword arguments, and they make calls easier to read and let you skip to the one you want.
*args in a def collects any number of extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dict. (The names are just a habit; the stars do the work.) That's how print() takes as many values as you like.
def total(*nums):
return sum(nums)
def describe(**info):
return ", ".join(f"{k}={v}" for k, v in info.items())
print(total(1, 2, 3, 4))
print(describe(name="Ana", age=31))
Prints
10
name=Ana, age=31
Scope is where a name can be seen. A variable assigned inside a function is local: it's separate from any variable with the same name outside. A function can read variables from outside (global ones), but assigning to the name inside makes a new local one. Pass values in and return them out rather than reaching outside.
A string on the first line of a function's body is its docstring: a short description that editors and help() show. Write one for anything you share.
The mutable default trap: a default value is made once, when the def runs, not on every call. If it's a list or dict and the function changes it, the change carries over to the next call. Use None as the default and make a fresh list inside.
def add_bad(item, basket=[]):
basket.append(item)
return basket
print(add_bad("egg"))
print(add_bad("milk"))
def add_good(item, basket=None):
"""Add item to basket, starting a new basket if none is given."""
if basket is None:
basket = []
basket.append(item)
return basket
print(add_good("egg"))
print(add_good("milk"))
Prints
['egg']
['egg', 'milk']
['egg']
['milk']
Practice
What does this print?
def power(base, exp=2):
return base ** exp
print(power(3), power(2, 5))
More info
Quick reference
def f(a, b=1):
b has a default value, used when it's left out.
f(b=2, a=1)
Keyword arguments: passed by name, any order.
*args / **kwargs
Collect extra positional arguments (tuple) / keyword arguments (dict).
local / global
Made inside the function / at the top level of the file.
docstring
A string first in the body that describes the function.
param=None
The safe default for a list or dict; make a fresh one inside.