Python Default & Keyword Arguments
A default argument is a parameter with a value ready when a call passes nothing. A keyword argument passes a value by parameter name.
The usual value written every time
Without a default, every usual call writes the same value again.
def greet(name):
print(f"Hello, {name}!")
greet("friend")
greet("friend")
greet("Ada")A default value
The parameter name has a default of friend. You may still pass your own value.
def greet(name="friend"):
print(f"Hello, {name}!")
greet()
greet("Ada")Keyword arguments
Name each argument in the call. The order can then change safely.
def show(name, city):
print(f"{name} lives in {city}.")
show(city="Paris", name="Ana")Mix the two styles
Give the first value by position. Give the rest by name.
def show(name, city):
print(f"{name} lives in {city}.")
show("Ana", city="Paris")Defaults come last
The required parameter item comes first here. The optional parameter size comes after it.
def order(item, size="medium"):
print(item, size)
order("tea")Example
def make_drink(size="medium"):
print(f"One {size} drink, please.")
make_drink()
make_drink("small")
make_drink("large")
make_drink(size="large")Key points
- Default value: a value a parameter uses when the call passes nothing for it
- Use a default value to make an argument optional
- Keyword argument: an argument passed by parameter name, like size="large"
- Put parameters with defaults after parameters without defaults
In this example, size has a default value of medium. The first call passes nothing, so size is medium. The second call passes small by position. The third call passes large by position. The last call passes large by keyword. Each call prints one drink line.
Note
In a call, positional arguments must come first.
Keyword arguments come after them.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Which call uses a keyword argument?