Default values and local names
A parameter with a default can be left out of the call. Names a function assigns are local: they exist only during the call and never change the names outside.
- Write a parameter with a default (
rate=0.08) and override it by position or by name - Explain that a name assigned inside a function is local to that call
- Fix an UnboundLocalError by passing the value in and returning the new one
Most calls to a tax function use the same rate. A default makes that rate optional: def with_tax(price, rate=0.08):. A call that leaves rate out gets 0.08; a call that passes it, by position or as rate=0.2, overrides it. Parameters with defaults go after the ones without.
Run each example to see what it prints. Running examples doesn't count toward progress.
def with_tax(price, rate=0.08): return price * (1 + rate) print(f"{with_tax(50):.2f}") print(f"{with_tax(50, 0.2):.2f}") print(f"{with_tax(rate=0, price=50):.2f}")
Each call gets its own fresh set of local names: the parameters and anything the body assigns. They disappear when the call ends, and they never touch a name with the same spelling outside. That isolation is what makes a function safe to call from anywhere.
The flip side surprises everyone once. If the body assigns a name anywhere, that name is local for the whole body, so reading it before the assignment fails even if an outer name exists.
visits = 0 def record_visit(): visits = visits + 1 record_visit()
def record_visit(visits, step=1): visits = visits + step return visits total = 0 visits = 10 total = record_visit(total) total = record_visit(total, 5) print(total, visits)
When to use it: give a default to a parameter that has a value most callers want (a standard rate, a usual threshold, a separator). Keep every working name local, and move data in through parameters and out through return. Mistakes to avoid:
- Putting a defaulted parameter before one without a default: that is a SyntaxError.
- Expecting an assignment inside a function to change an outer name.
- Using a list or dictionary as a default value: the same object is shared by every call. Use a number, text or None as a default.
def f(x, rate=0.08):makesrateoptional; a call can override it by position or by name.- Names assigned inside a function are local to the call and never change outer names.
- Move data in with parameters and out with return instead of changing outer names.
- Next: document what a function promises, and build bigger functions from small ones.