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.
What you’ll learn
Section titled “What you’ll learn”- How to define and call functions with the
defstatement. - The difference between positional and keyword arguments, and how default values work.
- How
returnworks, including returning multiple values and the implicitNonereturn. - How to add type hints and docstrings so your functions stay readable and tool-checkable.
Prerequisites
Section titled “Prerequisites”- Python 3.9 or newer installed (run
python --versionto check). - Comfort with variables, basic types, and
if/forcontrol flow. - Familiarity with running a script: save code as a
.pyfile and runpython filename.py.
1. Define a function with def
Section titled “1. Define a function with def”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 positionalcreate_order(item="Widget", customer="Alice", quantity=3) # all keywordcreate_order("Alice", "Widget", quantity=3) # mixedVerify: All three calls print 3 x Widget for Alice.
3. Add default values
Section titled “3. Add default values”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 defaultscreate_order("Bob", "Gadget", 5, "EUR") # overrides bothcreate_order("Cara", "Gadget", currency="GBP") # overrides one default by nameVerify: The first call prints 1 x Widget for Alice (USD), the second 5 x Gadget for Bob (EUR).
4. Return a value with return
Section titled “4. Return a value with return”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.97Verify: The script prints 219.97. If you remove the return keyword, total becomes None.
5. Return multiple values
Section titled “5. Return multiple values”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.98Verify: 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.
6. Add type hints
Section titled “6. Add type hints”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.98Verify: The script runs as before and prints 2 199.98. The hints are visible to a type checker but ignored at runtime.
7. Write a docstring
Section titled “7. Write a docstring”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.99help(apply_discount)Verify: The script prints 134.99 and then the docstring.
Complete working example
Section titled “Complete working example”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.47Common mistakes
Section titled “Common mistakes”- Using a mutable default argument.
def add_item(item, items=[]):shares the same list across every call that omitsitems, so it accumulates state. Useitems=Noneand create a fresh list inside the body. - Putting a default before a required parameter.
def f(a=1, b):is aSyntaxError. Defaults must follow parameters without defaults. - Forgetting
return. A function that computes a result but only prints it hands backNone. Usereturnto pass the value to the caller. - Returning when you meant to print.
return print(x)returnsNonebecauseprintreturnsNone. 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.
Next steps
Section titled “Next steps”- Lambda functions — short anonymous functions, often used with
sorted,map, andfilter. - 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.
Related pages
Section titled “Related pages”- Python basics index — overview of every basics page in one place.
- Python variables and data types — the types you pass into functions.
- Python comprehensions intro — building collections, which pairs well with helper functions.
- Functions and lambdas course page — the broader course chapter covering
*args,**kwargs, closures, and decorators.
Official references
Section titled “Official references”- docs.python.org: Defining functions — the
defstatement and the basics of defining functions. - docs.python.org: More on defining functions — default argument values, keyword arguments, and arbitrary argument lists.
- docs.python.org: Documentation strings — docstring conventions.
- docs.python.org: The
typingmodule — type hints for function signatures.