Functions and Objects · Functions · lesson 2 of 10
Parameters and defaults
about 12 minutes · free · runs in your browser
Step 1 of 2
Default values and keyword arguments
A parameter can have a default, which makes it optional:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
greet("Ada") # "Hello, Ada!"
greet("Ada", "Good morning") # "Good morning, Ada!"
greet("Ada", greeting="Hi") # naming it is clearer
Parameters with defaults must come after those without.
Naming arguments at the call site — greet(name="Ada") — makes calls readable when
there are several, and lets you skip past ones you are happy with.
One serious trap: never use a mutable default like def f(items=[]). The list is
created once, when the function is defined, and every call that relies on the default
shares it. Use None and build inside:
def f(items=None):
if items is None:
items = []
Your turn: write format_price(amount, currency="£", decimals=2) returning
something like "£9.99".
You start from this, and edit it in the browser:
def format_price(amount, currency="£", decimals=2):
# Return the amount with the currency in front.
pass
Step 2 of 2
The mutable default trap
This is worth writing once so it sticks:
def broken(item, basket=[]): # do not do this
basket.append(item)
return basket
broken("a") # ["a"]
broken("b") # ["a", "b"] ← the same list, still there
Your turn: write add_item(item, basket=None) that appends to the given basket, or
starts a fresh one when none is supplied — and does not share state between calls.
You start from this, and edit it in the browser:
def add_item(item, basket=None):
# Append item to basket, starting a new list when none is given.
pass