runtime
44 / 250
lesson 44 Functions · beginner

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.

You'll be able to
  • 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
The idea

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.

example-1.py · Tax with a usual rate
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.

example-2.py · Changing an outer counter
visits = 0

def record_visit():
    visits = visits + 1

record_visit()
example-3.py · Pass in, return out
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.
Review
  • def f(x, rate=0.08): makes rate optional; 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.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Default values and local names — Functions · Runtime