Reusable programs · 11 min

Scope and arguments

Use local names, defaults, and keyword arguments.

Names assigned inside a function usually belong to the current call. The caller can use a returned value, while the local names stay inside the function. Passing inputs explicitly makes each call easier to reason about.

A default such as tax=0.05 is used when the caller leaves that argument out. Call by keyword to show what a value means. Python evaluates defaults once when it defines the function. Use None and create a fresh list inside the function when you need a mutable default.

Follow the example

The function uses its default tax of 0.05.

Try it yourself

Print the result of calling price_with_tax on 200, first with the default tax and then with tax=0.20. Keep two decimal places.

Target output

210.00
240.00
Show a hint

You can reuse the function as written and change only the two calls.

Output

Ready

Run your code to see the output here.

The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.

Show one solution
def price_with_tax(price, tax=0.05):
    return price * (1 + tax)

print(f"{price_with_tax(200):.2f}")
print(f"{price_with_tax(200, tax=0.20):.2f}")