You write the same five-line calculation in three places, then need to fix a typo. With a function: fix it once, every caller gets the fix. Functions are how code stays maintainable.
def add_tax(amount, rate):
return amount * (1 + rate)
# Use it
total = add_tax(100, 0.08)
print(total) # 108.0
Five things to notice:
def — keyword that starts a function definition.add_tax — the function's name. Use snake_case.(amount, rate) — the parameters the function expects.if/for.return — sends a value back to the caller.add_tax(100, 0.08) # positional: amount=100, rate=0.08
add_tax(amount=100, rate=0.08) # keyword: same thing, more explicit
add_tax(rate=0.08, amount=100) # keyword: order doesn't matter
Use keyword arguments when you're calling a function with several parameters — it makes the call site readable.
def add_tax(amount, rate=0.08):
return amount * (1 + rate)
add_tax(100) # uses default rate of 0.08 → 108
add_tax(100, 0.10) # overrides → 110
Add a triple-quoted string right under def. Editors will show it as help when you hover the function name.
def add_tax(amount, rate=0.08):
"""Return amount + sales tax at the given rate."""
return amount * (1 + rate)
If you don't write return, Python returns None automatically. That's fine for functions whose job is to print something or save a file — their effect is what matters, not the return value.
def banner(msg):
line = "=" * len(msg)
print(line)
print(msg)
print(line)
banner("Monday report")
def name(params): defines a function.return sends a value back.celsius_to_fahrenheit(c) — return F.discounted_price(price, discount_pct=10) — return final price.full_name(first, last, middle="") — return a properly spaced full name.