HomeCourseModule 05 › def — defining your own function

def — defining your own function

Module 05 · Functions8 min readBeginner

What you'll learn

  • Write a function with parameters and a return value
  • Call it with positional and keyword arguments
  • Use a docstring to document it

Why functions matter

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.

The shape

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:

  1. def — keyword that starts a function definition.
  2. add_tax — the function's name. Use snake_case.
  3. (amount, rate) — the parameters the function expects.
  4. Colon, indented body — same as if/for.
  5. return — sends a value back to the caller.

Positional vs keyword arguments

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.

Default values

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

Docstrings

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)

Functions that don't return a value

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")

Key takeaways

  • def name(params): defines a function.
  • return sends a value back.
  • Use keyword arguments for clarity.
  • Default parameters give callers an opt-in override.

Write three functions

  1. celsius_to_fahrenheit(c) — return F.
  2. discounted_price(price, discount_pct=10) — return final price.
  3. full_name(first, last, middle="") — return a properly spaced full name.
📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.