Parameters & Arguments
Functions become truly useful when you can pass information into them. Parameters are the variable names listed in a function's definition; arguments are the actual values you pass when you call it. Python offers several flexible ways to match one to the other.
Parameters vs. arguments
def greet(name, town): # name and town are parameters
print(f"Habari {name} from {town}!")
greet("Amani", "Thika") # "Amani" and "Thika" are arguments
When the function is called, each parameter becomes a local variable holding the matching argument. People often use the two words loosely, but the distinction helps when reading error messages.
Positional arguments
By default, arguments are matched to parameters by position: first to first, second to second. Order matters.
def transfer(amount, recipient):
print(f"Sending KES {amount} to {recipient}")
transfer(500, "Njeri")
transfer("Njeri", 500) # wrong order: no error, but nonsense
You must also pass the right number of arguments. Calling transfer(500) stops with TypeError: transfer() missing 1 required positional argument: 'recipient'.
Keyword arguments
You can name the parameter when you call the function. With keyword arguments, order no longer matters and calls become self-explanatory.
transfer(recipient="Njeri", amount=500) transfer(750, recipient="Hassan")
Positional arguments must come before keyword arguments. transfer(amount=500, "Njeri") is a SyntaxError (positional argument follows keyword argument).
Default values
Give a parameter a default with = in the definition. If the caller leaves that argument out, the default is used. Parameters with defaults must come after those without.
def describe_pet(name, animal="dog"):
print(f"{name} is a {animal}.")
describe_pet("Simba")
describe_pet("Kibo", "cat")
describe_pet(animal="parrot", name="Kasuku")
You've used defaults already: print() has sep=" " and end="\n" as defaults, which is why you only pass them when you want something different.
Using a mutable default such as a list. A default value is created once, when the function is defined, not on every call. So a list default is shared between calls and keeps growing:
def add_item(item, basket=[]):
basket.append(item)
return basket
print(add_item("mango"))
print(add_item("banana")) # surprise!
The fix is to default to None and create a fresh list inside the function:
def add_item(item, basket=None):
if basket is None:
basket = []
basket.append(item)
return basket
print(add_item("mango"))
print(add_item("banana"))
Any number of arguments: *args
A parameter with a single star collects any number of extra positional arguments into a tuple. The name args is just a convention; the star is what matters.
def total(*amounts):
print("Received:", amounts)
return sum(amounts)
print(total(100, 250, 50))
print(total())
Any number of keyword arguments: **kwargs
A double star collects extra keyword arguments into a dictionary.
def profile(**details):
for key, value in details.items():
print(f"{key}: {value}")
profile(name="Amina", county="Kilifi", age=20)
Unpacking arguments when calling
The stars also work in the other direction: * spreads a list or tuple into positional arguments, and ** spreads a dictionary into keyword arguments.
def transfer(amount, recipient):
print(f"Sending KES {amount} to {recipient}")
details = (300, "Baraka")
transfer(*details)
order = {"recipient": "Zawadi", "amount": 1200}
transfer(**order)
Keyword-only parameters
Parameters placed after a bare * in the definition must be passed by keyword. This prevents confusing calls where values are easy to mix up.
def send_money(amount, *, to):
print(f"KES {amount} sent to {to}")
send_money(500, to="Achieng")
Calling send_money(500, "Achieng") raises TypeError: send_money() takes 1 positional argument but 2 were given. (The opposite also exists: parameters before a / are positional-only, which you'll mostly see in the documentation of built-in functions.)
Order of parameters
When you combine these features in one definition, use this order:
def example(a, b=2, *args, c, d=4, **kwargs):
print(a, b, args, c, d, kwargs)
example(1, 5, 6, 7, c=3, e=9)
Regular parameters, then defaults, then *args, then keyword-only parameters, then **kwargs. In practice, keep functions simple; most need only two or three parameters.
Key points
- Parameters are names in the definition; arguments are the values passed in a call.
- Positional arguments match by order; keyword arguments match by name and must come after positional ones.
- Defaults make arguments optional, but never use a mutable default like
[]; useNone. *argsgathers extra positional arguments into a tuple and**kwargsgathers extra keyword arguments into a dictionary.- Parameters after a bare
*are keyword-only.
Tip: use the ← and → keys to move between pages.
