← Intro to programming with Python

Default values and scope

Optional parameters, and where variables live.

Start this lesson

A parameter can have a default value, used when the caller leaves it out: def make_tea(sugar=0):. This keeps common calls short while still allowing changes. The other idea here is scope: variables created INSIDE a function are local. They exist only while the function runs and cannot be seen outside it. That is a good thing: each function is its own little room, so a variable named total in one function cannot clash with a total somewhere else.

def price_with_tip(bill, percent=15):
    tip = bill * percent / 100
    return bill + tip

print(price_with_tip(40))       # 46.0 (uses 15)
print(price_with_tip(40, 20))   # 48.0
# print(tip)  would be a NameError: tip lives only inside the function

percent is optional because it has a default. tip is local, so it disappears when the function returns.

Common mistake: trying to use a function's local variable outside it. Return the value instead, and store it: t = price_with_tip(40).

Parameters with defaults must come AFTER the ones without: def f(a, b=2): is fine, def f(a=1, b): is an error.

You can name arguments in the call to make it clearer: price_with_tip(40, percent=18).