Python Default Parameter Values
Core idea
A parameter such as fee=3 has a default value. When a call omits that argument, Python uses the default. The expression is evaluated when the definition executes, not again on every call. Ordinary required positional-or-keyword parameters precede those with defaults.
def total(price, fee=3): return price + fee
print(total(10))print(total(10, fee=1))Omission uses 3; an explicit argument overrides it.
Capture a definition-time value
rate = 4def cost(count, unit=rate): return count * unit
rate = 8print(cost(2))print(cost(2, rate))Rebinding rate does not change the stored default 4.
Explicit zero is not omission
def total(price, fee=3): return price + fee
print(total(10, 0))Zero fills the parameter; the default is not used.
Common mistake
def total(fee=3, price): is invalid syntax. Do not expect a default to be recalculated each call; calculate dynamic values in the body instead.
Practice
Define a function for the total length of a batch, with a default unit length of 4. Try omission and an explicit zero.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Default values
Check your understanding of defaults.
What is printed?
def total(n, fee=3): return n + feeprint(total(6))What is printed?
def total(n, fee=3): return n + feeprint(total(6, 0))What is printed?
rate = 4def get(unit=rate): return unitrate = 9print(get())When does Python evaluate a default expression?