How it works
Python passes references to objects. Rebinding a parameter inside a function does not affect the caller, but mutating a mutable argument does.
Decide for each parameter whether the function may modify it, and document that.
Common error
Mutating a list argument unintentionally, which changes the caller data invisibly.
Worked example
Python
def scale(value, factor):
return value * factor
print(scale(4, 3))Output
12Arguments in the call supply the values used by local parameter names. Reusing the function with different arguments avoids duplicating the calculation.
Exercises
2.1.1 · Trace
Determine the exact output and explain the state changes.
Python
def change(values):
values.append(9)
data = [1]
change(data)
print(data)Show solution
Output
[1, 9]The local parameter refers to the caller list, so mutation is visible.
2.1.2 · Write code
Write add_tax(price, rate) and show a price of 100 at rate 0.08.
Show solution
Return the price multiplied by one plus the rate.
One valid solution
def add_tax(price, rate):
return price * (1 + rate)
print(add_tax(100, 0.08))Expected output
108.0