Default & keyword arguments
A parameter can have a default that is used when the caller leaves it out:
def brew(size="medium", sugar=0): return f"{size} coffee, {sugar} sugar"
brew() # medium coffee, 0 sugar brew("large") # large coffee, 0 sugar brew(sugar=2) # keyword argument: pick by name
Keyword arguments can come in any order.
See it run
def brew(size="medium", sugar=0): return f"{size}, {sugar} sugar" a = brew() b = brew("large") c = brew(sugar=2)
Each call opens a fresh brew() box. Watch which values are filled in for you.
Practice default & keyword arguments
Exercise 1
- Define
power(base, exp=2)that returns base to the power exp. - Set
result = power(exp=3, base=2)using keyword arguments (8).
Exercise 2
Define ticket(price, quantity=1, fee=0) returning price * quantity plus a single booking fee. Store booking by calling ticket with price 8, quantity 3, fee 2 using keyword arguments in any order.
Exercise 3
Define shipping(weight, rate=3, express=False). Base shipping is weight * rate; express adds a flat 5. Store quote for weight 2, rate 4 and express True using keywords. Zero weight still pays the express fee if requested.
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.