Sub topic 2
Giving Parameters Default Values
Assume you know variables, lists, dictionaries, if statements, and basic function calls. A parameter is a name in a function definition. An argument is the value supplied by the caller.
Default parameter values
A default value is used when the caller omits an argument. Parameters with defaults must come after required parameters.
def power(base, exponent=2):
return base ** exponent
print(power(5)) # 25
print(power(2, 10)) # 1024
print(power(base=2, exponent=3)) # 8The expression for a default value is evaluated once, when Python creates the function. This matters for mutable objects such as lists and dictionaries.
Use None as a marker and create a new object inside the function:
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item("tea")) # ['tea']
print(add_item("bread")) # ['bread']Returning several values at once
A return statement can contain several expressions. Python packages them into a tuple, which the caller can unpack into separate variables.
def min_max(values):
return min(values), max(values)
low, high = min_max([3, 1, 4, 1, 5])
print(low, high) # 1 5Local scope
Scope is the region where a name can be used. Parameters and names assigned inside a function normally have local scope. They disappear when the call finishes and do not replace a name with the same spelling outside the function.
name = "outside"
def greet():
name = "inside"
return name
print(greet()) # inside
print(name) # outsideWhat happens to an argument
Python passes an object reference into the parameter. Rebinding the parameter does not change the caller's variable, but mutating a shared mutable object does.
def change(number, items):
number = 99
items.append("new")
values = ["old"]
change(1, values)
print(values) # ['old', 'new']Exercise
Why does number remain unchanged while items gains an element?
Show answer
Reassigning the local parameter number changes only that local name. items and values refer to the same list, so appending mutates the shared object.