Default and keyword arguments

Functions, lesson 3 of 6

🧩 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.

Example

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.

Example

Book a flight

print uses keyword arguments too: try print("a", "b", sep="-").

Quiz

What does this print?

Exercise

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.

Example

A cart that remembers too much

Both calls share the same default list, so the pear lands next to the apple.

Example

The fix: default to None

Now every call without a cart gets a brand new list.

Exercise

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.

Quiz

Which of these def lines is a SyntaxError?