Python ยท Chapter 20 of 45
Default & Keyword Arguments
Parameters can have default values, so callers don't have to pass them.
You can also pass arguments by NAME (keyword arguments), which improves readability.
Defaults
Default arguments must come AFTER non-default ones in the signature.
Keyword arguments
Passing `func(x=1, y=2)` is called keyword-argument style. It makes call sites self-documenting.
Example 1 (python)
def power(base, exp=2):
return base ** exp
print(power(5))
print(power(5, exp=3))Output
25
125exp defaults to 2 unless specified.
Example 2 (python)
def order(item, qty=1, size="medium"):
return f"{qty} {size} {item}"
print(order("coffee", size="large"))Output
1 large coffeeNamed arguments can be given in any order.
Key points
- Defaults go AFTER required parameters.
- Keyword calls: `func(name=value)`.
- Improves readability at call sites.
- Never use a mutable object (like a list) as a default value.
๐ก Note: Avoid `def f(x=[]):` โ the same list is reused across calls. Use `def f(x=None):` and set it inside the function.
