Functions
A function gives a name and a boundary to a repeatable piece of work.
Reach for it whenUse a function instead of copied code when one job repeats or deserves its own test; keep a tiny one-off expression inline when a name would obscure it.
Think of it likeA vending machine. You put something in, a fixed process happens, something comes out. You do not need to know what happens inside to use it.
You define one with def, a name, and brackets listing what it needs: def add(a, b): followed by an indented block. The names in brackets are called parameters — they refer to whatever gets passed in when the function runs.
The word return sends a value back to whoever called the function, and immediately stops the function. Anything written after a return never runs.
def greet(name):- Defines a function. The body is the indented block below.
return value- Hands a result back to the caller and stops the function.A function with no return gives back None.
def greet(name, greeting="Hi"):- A default, used when the caller omits that argument.
greet(name="Ada")- A keyword argument. Clearer than position once there are several.
def total(*numbers):- Collects any number of positional arguments into a tuple.
def config(**options):- Collects any number of keyword arguments into a dictionary.
def add(a: int, b: int) -> int:- Type hints. Python does not enforce them; they are for readers and tools.
"""One line saying what it does."""- A docstring, the first thing in the body. help(add) prints it.
Python binds argument values to parameter names, creates local variables as the body runs, and discards that frame when the call returns. Calling the same function twice therefore does not reuse the first call's locals.
Copying three lines saves no thinking if callers still need to understand every step. A good function names a stable responsibility and lets its implementation change without changing its callers.
Default arguments are evaluated once when `def` runs, not afresh for each call. Use `None` as the default and create the list inside when each call needs independent state.
- FastAPI — calls Python functions registered as handlers when matching HTTP requests arrive.
- pytest — discovers named test functions and calls them with requested fixtures.
- "A function must print its result." Correction: return hands a value to the caller; printing only displays it.
- "Parameters are arguments." Correction: parameters are the function's names; arguments are the values supplied by a call.