Functions
A function is a named, reusable block of code you call with arguments. def creates one, parameters receive the values, and return sends a result back to the caller.
Detailed Explanation
A function exists so you can give a piece of work a name and a contract. def charge(order_id, cents): says: callers give you an order and an amount, you do the charging, they get a result. The body is indented under def. Execution jumps into the body on a call and returns to the caller on return or when the body ends.
If you omit return, or write return with no value, the function returns None. That is why items = items.sort() is a bug: sort returns None after mutating the list. Returning None implicitly is fine for commands that only have side effects. It is a problem when the caller expected data.
Parameters are names bound in the function's local scope when the call happens. Positional arguments fill parameters from the left. Keyword arguments fill parameters by name and can appear after positionals. Defaults fill anything still empty. Extra positionals and keywords are collected by *args and **kwargs. The binding rules, and the mutable-default trap, have their own entries.
A function is an object. def binds that object to a name in the current scope. You can assign it to another name, put it in a list, pass it as an argument, or return it. That is first-class functions. lambda builds a small anonymous function; def is the form you want whenever there is a name, a docstring, or more than one expression.
Python does not have required type checks at runtime. Annotations such as def area(width: int) -> int are stored on the function as __annotations__ and used by checkers and documentation. The interpreter will still call area("wide") unless you add a validator.
Functions can nest. An inner function sees the outer function's locals through a closure. Decorators, callbacks, and factories all depend on that. Recursion is a function calling itself; Python keeps a finite call stack (often 1000 frames) and raises RecursionError when it runs out.
Docstrings are the first string literal in the body. They become __doc__ and are what help(func) shows. Write one sentence about what the function does, not how.
Code Examples
def charge(order_id: str, cents: int, *, currency: str = "USD") -> dict:
"""Record a payment. `currency` must be passed by name."""
if cents <= 0:
raise ValueError("cents must be positive")
return {"order_id": order_id, "cents": cents, "currency": currency}
receipt = charge("ORD-11", 2500, currency="EUR")
print(receipt["cents"]) # 2500
print(charge("ORD-12", 100)) # currency defaults to USD# No return means None. Callers that expect a value will see it.
def log_total(amounts: list[int]) -> None:
print(sum(amounts))
result = log_total([10, 20]) # 30
print(result) # None# A function is an object you can pass.
def twice(func, value):
return func(func(value))
print(twice(lambda n: n + 1, 3)) # 5Common Gotchas
Forgetting `return` yields `None`
the function ran, the caller got nothing useful. Look for assignments of a function that mutates in place.
Parameters are local names
assigning to a parameter does not change the caller's variable. Rebinding `cents = 0` inside `charge` leaves the caller's integer alone. Mutating a list argument does change the caller's list.
Defaults are evaluated once
`def append(item, bucket=[])` reuses one list. Use `None` and create the list in the body.
A bare `return` is `return None`
be explicit when `None` is a meaningful result, so callers can tell it from a missing `return`.