Default arguments
Sometimes a parameter has a sensible default, and you'd rather not force the caller to supply it every time. Python lets you give a parameter a default value.
Giving a parameter a default
Assign a value in the def line. That value is used whenever the caller leaves the argument out:
Python
The first call doesn't pass greeting, so Python uses "Hello". The second call passes "Hi", which overrides the default.
The rule: defaults come last
Parameters with defaults must come after parameters without them:
Python
This keeps Python from getting confused about which argument is which.
Key takeaways
- A default value is given in the def:
def f(x, y=10):. - Callers can omit a defaulted argument or pass one to override it.
- Parameters with defaults must come after those without.
No comments yet. Add the first comment to start the discussion.