Default parameter values
A parameter can have a default value, written with = after its name in the def line. When a call leaves that argument out, the parameter gets the default:
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Ada")
greet("Linus", "Good morning")
greet("Grace", "")
Hello, Ada!
Good morning, Linus!
, Grace!The last call shows that an empty string is still an argument: the default is used only when the argument is missing. You've relied on defaults all along: print puts a line break at the end unless you give end=..., and range(5) starts from 0 unless you give it a start.
Keyword arguments
With several defaults, a call can name the parameter it gives with a keyword argument, as you've done with sep= and end= in print, and keep the defaults of the others:
def line(length=20, character="-"):
return character * length
print(line())
print(line(5))
print(line(8, "="))
print(line(character="*"))
--------------------
-----
========
********************Parameters with a default come after those without one. The other way round, Python couldn't tell which argument belongs to which parameter, and it stops before running anything:
def greet(greeting="Hello", name):
print(f"{greeting}, {name}!")
File "main.py", line 1
def greet(greeting="Hello", name):
^^^^
SyntaxError: parameter without a default follows parameter with a defaultA list as a default: a trap
A default value is made once, when the def line runs, not on every call. For a number or a string that doesn't matter. But a list can change, and then every call that uses the default shares the same list:
def add_item(item, basket=[]):
basket.append(item)
return basket
print(add_item("apple"))
print(add_item("pear"))
['apple']
['apple', 'pear']The second call got a basket that already had an apple in it. The usual fix is None as the default, and a new list made inside the function: def add_item(item, basket=None):, with if basket is None: and basket = [] at the start of the body.