Lesson 3 of 10
A parameter can have a default value, used whenever the caller doesn't supply one.
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Ada")
greet("Grace", "Welcome")
greeting="Hello" makes that parameter optional. Callers who don't care get sensible behaviour;
callers who do care can override it.
Defaults come last
Parameters with defaults must come after parameters without them:
def greet(greeting="Hello", name):
print(f"{greeting}, {name}!")
That is a SyntaxError. Python has no way to tell which argument you meant if the optional one
came first. Required parameters first, optional ones after.
Several defaults
def make_user(name, role="member", active=True):
return {"name": name, "role": role, "active": active}
print(make_user("Ada"))
print(make_user("Grace", "admin"))
print(make_user("Alan", active=False))
That last call skips role and jumps straight to active by naming it. Without keyword
arguments you'd have to pass role just to reach active.
The mutable default trap
This one bites every Python programmer eventually:
def add_item(item, basket=[]):
basket.append(item)
return basket
print(add_item("apple"))
print(add_item("banana"))
You'd expect ['apple'] then ['banana']. You actually get ['apple'] then
['apple', 'banana'].
The reason: the default value is created once, when the function is defined — not each time it's called. Every call that relies on the default shares the same list.
The fix is to default to None and create a fresh list inside:
def add_item(item, basket=None):
if basket is None:
basket = []
basket.append(item)
return basket
print(add_item("apple"))
print(add_item("banana"))
Rule: never use a list, dictionary, or set as a default value. Use None and build it
inside the function.
Try it yourself
Write greet(name, greeting="Hello") and call it both ways.
Checkpoint
param=valuemakes a parameter optional.- Parameters with defaults must come after those without.
- Keyword arguments let you skip over optional parameters.
- Never default to a mutable value — use
Noneand create it inside.
Questions about this lesson
Log in to ask a question.