A default argument is a parameter with a value already filled in. If the caller does not pass that argument, Python uses the default.
The program
python
def greet(name, greeting="Hello"): return f"{greeting}, {name}!" print(greet("Ada")) print(greet("Linus", "Hi")) print(greet("Grace", greeting="Good morning"))
output
Hello, Ada! Hi, Linus! Good morning, Grace!
How it works
greeting="Hello"sets the default. The first call passes onlyname, sogreetingis"Hello".- The second call passes a value by position, and the third passes it by name (a keyword argument). Both replace the default.
- Parameters with defaults must come after the ones without.
def greet(greeting="Hello", name):is aSyntaxError.
The mutable default mistake
The default value is created once, when Python runs the def line. It is not created again on each call. With a list as the default, every call shares the same list:
python
def add_item(item, basket=[]): basket.append(item) return basket print(add_item("apple")) print(add_item("bread"))
output
['apple'] ['apple', 'bread']
The second call still sees "apple" from the first call. Use None as the default and create a new list inside the function:
python
def add_item(item, basket=None): if basket is None: basket = [] basket.append(item) return basket print(add_item("apple")) print(add_item("bread"))
output
['apple'] ['bread']