Skip to content

Python Functions: def, Parameters, and Return Values

Functions are how you keep Python code repeatable and testable. Instead of copying the same logic into every order pipeline, you wrap it in a named function once and call it from anywhere. This tutorial uses OrdersPortal, a small order-management system, to show each idea in a realistic setting. By the end you will be writing typed, documented functions that a team can read and a type checker can verify.

  • How to define and call functions with the def statement.
  • The difference between positional and keyword arguments, and how default values work.
  • How return works, including returning multiple values and the implicit None return.
  • How to add type hints and docstrings so your functions stay readable and tool-checkable.
  • Python 3.9 or newer installed (run python --version to check).
  • Comfort with variables, basic types, and if/for control flow.
  • Familiarity with running a script: save code as a .py file and run python filename.py.

A function bundles a block of code under a name so you can run it from anywhere. Use def, give it a name, list any parameters in parentheses, then indent the body. The body runs only when the function is called.

def greet_customer(name):
print(f"Welcome to OrdersPortal, {name}!")
greet_customer("Alice")

Verify: Run the script. The output prints Welcome to OrdersPortal, Alice!.

2. Accept positional and keyword arguments

Section titled “2. Accept positional and keyword arguments”

Arguments are the values you pass in. Positional arguments are matched by order. Keyword arguments are matched by name, which makes calls self-documenting and lets you skip earlier parameters when later ones have defaults.

def create_order(customer, item, quantity):
print(f"{quantity} x {item} for {customer}")
create_order("Alice", "Widget", 3) # all positional
create_order(item="Widget", customer="Alice", quantity=3) # all keyword
create_order("Alice", "Widget", quantity=3) # mixed

Verify: All three calls print 3 x Widget for Alice.

A parameter with a default value becomes optional. Defaults must come after parameters that have no defaults, because Python matches arguments left to right.

def create_order(customer, item, quantity=1, currency="USD"):
print(f"{quantity} x {item} for {customer} ({currency})")
create_order("Alice", "Widget") # uses both defaults
create_order("Bob", "Gadget", 5, "EUR") # overrides both
create_order("Cara", "Gadget", currency="GBP") # overrides one default by name

Verify: The first call prints 1 x Widget for Alice (USD), the second 5 x Gadget for Bob (EUR).

print shows output but does not hand data back to the caller. Use return to produce a value the rest of your program can use. A function with no return (or a bare return) returns None.

def order_total(prices):
return sum(prices)
total = order_total([149.99, 49.99, 19.99])
print(total) # 219.97

Verify: The script prints 219.97. If you remove the return keyword, total becomes None.

Python functions can return several values at once by packing them into a tuple. The caller unpacks them with the same number of names. This is a clean way to return related results without a custom class.

def summarize_order(items):
count = len(items)
total = sum(items)
return count, total # packed into a tuple
count, total = summarize_order([149.99, 49.99])
print(count, total) # 2 199.98

Verify: The script prints 2 199.98. The single returned value is a tuple, so result = summarize_order(...) gives you (2, 199.98) if you prefer not to unpack.

Type hints document what types a function expects and returns. They do not change runtime behavior, but tools such as mypy and Pyright check them and report mismatches before you run the code. In production code, add them to any non-trivial function.

def order_total(prices: list[float]) -> float:
return sum(prices)
def summarize_order(items: list[float]) -> tuple[int, float]:
return len(items), sum(items)
count, total = summarize_order([149.99, 49.99])
print(count, total) # 2 199.98

Verify: The script runs as before and prints 2 199.98. The hints are visible to a type checker but ignored at runtime.

A docstring is a triple-quoted string right after the def line. It documents the function’s purpose, parameters, and return value, and tools such as help() and IDEs display it. The first line is a short summary; the rest adds detail.

def apply_discount(amount: float, percent: float) -> float:
"""Return the price after applying a discount.
Args:
amount: The original order amount.
percent: The discount percentage, from 0 to 100.
Returns:
The discounted amount, rounded to two decimals.
"""
return round(amount * (1 - percent / 100), 2)
print(apply_discount(149.99, 10)) # 134.99
help(apply_discount)

Verify: The script prints 134.99 and then the docstring.

Save this as orders_functions.py and run python orders_functions.py.

"""OrdersPortal order helpers."""
def create_order(customer: str, item: str, quantity: int = 1, currency: str = "USD") -> dict:
"""Build an order record."""
return {
"customer": customer,
"item": item,
"quantity": quantity,
"currency": currency,
"line_total": None, # filled in below
}
def price_order(order: dict, unit_price: float) -> float:
"""Return the order total including the unit price."""
return round(unit_price * order["quantity"], 2)
def summarize(orders: list[dict]) -> tuple[int, float]:
"""Return the count of orders and their combined total."""
return len(orders), round(sum(o["line_total"] for o in orders), 2)
# --- script entry point ---
if __name__ == "__main__":
order_a = create_order("Alice", "Widget", 3)
order_a["line_total"] = price_order(order_a, 9.99)
order_b = create_order("Bob", "Gadget") # quantity defaults to 1
order_b["line_total"] = price_order(order_b, 24.50)
count, total = summarize([order_a, order_b])
print(f"{count} orders, total {total:.2f}")

Expected output:

2 orders, total 54.47
  • Using a mutable default argument. def add_item(item, items=[]): shares the same list across every call that omits items, so it accumulates state. Use items=None and create a fresh list inside the body.
  • Putting a default before a required parameter. def f(a=1, b): is a SyntaxError. Defaults must follow parameters without defaults.
  • Forgetting return. A function that computes a result but only prints it hands back None. Use return to pass the value to the caller.
  • Returning when you meant to print. return print(x) returns None because print returns None. Return the value directly instead.
  • Overusing keyword arguments. Forcing every caller to write create_order(customer="Alice", ...) adds noise. Use keyword arguments when they improve clarity, not as a blanket rule.
  • Lambda functions — short anonymous functions, often used with sorted, map, and filter.
  • Scope — how names inside a function stay local, and how closures capture variables.
  • Decorators intro — wrapping functions to add behavior without changing their code.
  • Type hints — deeper coverage of annotations for parameters, return types, and generics.