🧩 Functions, lesson 3 of 6
Default and keyword arguments
Make parameters optional and calls readable, and dodge the mutable default trap.
11 min
2 exercises
2 quizzes
0/4 solved
Getting Python ready… examples can run in a moment.
Give a parameter a default value with = in the
def line. Callers can then leave it out.
Parameters with defaults must come after those
without.
Coffee order
Give order a third parameter, milk="oat", and use it in the message.
Keyword arguments name the parameter in the call:
order(sugars=2). They can go in any order, make
calls self-explanatory, and let you skip the
defaults you don't care about. Positional arguments
must come first.
Book a flight
print uses keyword arguments too: try print("a", "b", sep="-").
What does this print?
Split the bill
Finish split_bill(bill, tip=15, people=1). It
returns what each person pays: the bill plus a
tip percent, divided by people, rounded to 2
decimals.
split_bill(100) → 115.0 and
split_bill(90, people=3) → 34.5.
A cart that remembers too much
Both calls share the same default list, so the pear lands next to the apple.
The fix: default to None
Now every call without a cart gets a brand new list.
Fix the leaky scores
add_score has the mutable default bug: scores from
earlier calls leak into later ones. Fix it so a call
without a list always starts from a fresh empty
list, while a call with a list still appends to
that list.
Which of these def lines is a SyntaxError?