Inputs with good defaults.
Use defaults and keyword arguments to make functions pleasant to call.
01 The idea
Parameters describe the inputs a function accepts. Default values make some inputs optional. Keyword arguments identify an input by name, making calls clearer when several values have similar types. Required parameters must be provided unless a default exists.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
def mission_label(name, priority="normal"):
return f"{name}: {priority}"
print(mission_label("Orbit"))
print(mission_label("Orbit", priority="high"))Orbit: normal Orbit: high
03 Under the hood
- 1
The first call omits priority, so the default "normal" is used. The second call overrides it by name.
- 2
Defaults are evaluated when Python executes the function definition, not afresh for every call. That matters when a default is mutable.
- 3
To collect optional items safely, use a None default and create a new list inside the function. *args can collect extra positional arguments; **kwargs can collect extra named arguments when an interface needs that flexibility.
04 Your turn, builder
Write greet(name, greeting="Hello") and call it once with the default and once with greeting="Hey".
Reveal one possible solution +
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Navan"))
print(greet("Navan", greeting="Hey"))05 Check your signal
When is a default parameter value evaluated?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.