Lesson 11 of 52Functions
Functions
Define functions with def, pass arguments, return values instead of printing them, and write small pure functions.
You can now store data in collections and reshape it with comprehensions. The next step is to package your own logic so you can reuse it. Functions are how you stop repeating yourself and start building things out of parts. Every real codebase is mostly functions: calculate_tax, send_welcome_email, parse_date. Good functions are small, named after what they do, and easy to test, and the habits from this lesson (return instead of print, pure where possible, early returns) are exactly what code reviewers look for.
Defining and calling
def creates a function. It has a name, a list of parameters in parentheses, a colon, and an indented body. Nothing in the body runs until you call the function by writing its name with parentheses.
Press Run (⌘ Enter) to see what happens.Two words get mixed up constantly, so pin them down now:
- A parameter is the name in the definition:
nameindef greet(name). - An argument is the actual value you pass when calling:
"Ada"ingreet("Ada").
When the function is called, Python ties the parameter name to the argument object (the same name-tag idea from the variables lesson) and runs the body.
The caller passes two arguments. Inside area, the parameters width and height are tied to 3 and 4.
Press Run (⌘ Enter) to see what happens.return vs print
This is the most important distinction in the lesson. print shows a value to a human. return hands a value back to the code that called the function, so it can be stored, combined and tested.
A function without a return statement still returns something: None.
Press Run (⌘ Enter) to see what happens.If a function prints its answer, you cannot use that answer anywhere else. Prefer returning, and let the caller decide whether to print.
What does this print?
def shout(word):
print(word.upper())
result = shout("hi")
print(result)f() return?def f(): return 1 return 2
Returning several values
A function returns exactly one object, but that object can be a tuple. Combined with unpacking, it feels like returning several values.
Press Run (⌘ Enter) to see what happens.Docstrings
A docstring is a string literal as the first line of a function body. It documents what the function does, and tools read it: help(fn) prints it, and editors show it on hover.
Press Run (⌘ Enter) to see what happens.The : float and -> float parts are type hints: notes saying what types the parameter and return value should be. Python does not enforce them at runtime, but they make the function's contract clear and let tools catch mistakes. Keep the docstring to one line when the name and hints already explain most of it.
Functions are objects with attributes
def is not a declaration that the compiler files away. It is a statement that runs, builds a function object, and binds it to a name, exactly like x = 5 binds a number. That object carries information about itself, and a lot of Python tooling reads it.
Press Run (⌘ Enter) to see what happens.What each one is for:
__name__and__qualname__are what logs, tracebacks and metrics use.__qualname__includes the class or enclosing function, such asOrder.total. Decorators that forget to copy them make every log line saywrapper(Decorators shows the fix,functools.wraps).__doc__is the docstring.help(), editors and documentation generators read it.__defaults__and__kwdefaults__hold the default values. They are computed once, whendefruns, and stored on the object. That is the whole explanation of the mutable default trap from Arguments, *args and **kwargs: the same list sits in__defaults__and every call appends to it.__code__is the compiled bytecode and its metadata. You rarely touch it directly, but debuggers and profilers do.- Custom attributes are occasionally useful for registries and test markers. Frameworks often attach metadata this way.
Because functions are values, you can put them in dicts, pass them as arguments and return them from other functions. Higher-Order Functions builds on exactly that, and Scope and Closures shows functions that carry data with them.
What does this print?
def tag(label, seen=[]):
seen.append(label)
return len(seen)
tag("a"); tag("b")
print(tag("c"), tag.__defaults__)Pure functions and side effects
A pure function depends only on its arguments and only produces a return value. Same input, same output, every time, and nothing else in the world changes. area and to_celsius are pure.
A side effect is anything else a function does: printing, writing a file, changing a global variable, mutating a list it was given, sending a request.
Press Run (⌘ Enter) to see what happens.Programs need side effects to be useful, but pure functions are far easier to test and reason about. A good design keeps the logic pure and pushes the side effects (printing, saving) to the edges.
Is each function pure, or does it have a side effect?
Command-query separation in practice
A useful rule for deciding what a function returns: every function should be either a command or a query, not both.
- A query answers a question and changes nothing. Calling it twice is harmless.
total(cart),is_valid(row),find_user(email). - A command changes something (state, a file, a database, the outside world) and returns
None, or at most a small status such as the id of the row it created.
Python's own built-ins follow this rule, and it explains a bug every beginner writes once:
Press Run (⌘ Enter) to see what happens.list.sort(), list.append(), dict.update() and random.shuffle() return None on purpose, so you cannot chain them and mistake a mutation for a fresh value. When you see x = x.sort() in a review, that is the bug.
The rule bends where it makes sense. dict.pop(key) and list.pop() both change the container and return a value, because "remove and give it to me" is one operation. A function that inserts a row and returns its new id is fine. What you avoid is a function named like a question that quietly changes things: get_user() that also updates last_seen, or is_expired() that deletes the session. Those surprise whoever calls them, and they make retries and caching dangerous.
At the scale of a whole program, the same idea is called functional core, imperative shell: keep the decisions in pure functions, and confine reading input and writing output to a thin outer layer.
The outer function is the shell. It orchestrates, but makes no business decisions itself.
What does this print?
names = ["sam", "ada"] names = names.sort() print(names)
Early return
Deeply nested if blocks are hard to read. An early return (also called a guard clause) handles the special cases first and gets out, leaving the main logic flat.
Press Run (⌘ Enter) to see what happens.Each guard answers one question and returns. By the time you reach the last line, you know every special case has been dealt with. Returning from inside a loop works the same way: it stops the loop and the function at once, which is perfect for "find the first match".
Order the lines to make a function that returns the first word longer than 5 letters, or None.
- Tap the steps below in the right order.
Designing signatures
A function's signature (its name, parameters and return type) is a promise to every caller. Once it is used in fifty places, changing it is expensive, so a few minutes of design up front pays back for years. These are the habits reviewers look for:
Keep parameters few. Three or four is comfortable. Past that, callers start passing values in the wrong order, and it usually means the function does too much or a group of parameters belongs together in a dataclass (Address instead of street, city, postcode, country).
Make flags keyword-only. A call like send_invoice(42, 9.99, True) tells the reader nothing. Put a bare * before the options so callers must write dry_run=True. The syntax is covered in Arguments, *args and **kwargs; the design point is that keyword-only parameters can also be reordered or added later without breaking anyone.
Treat a boolean flag as a smell. If a flag switches between two different behaviours, export(data, as_csv=True), two functions (export_csv, export_json) are usually clearer and easier to test.
Return one type, consistently. A function that returns a list sometimes and None other times forces every caller to check. Decide what "nothing" means:
- "Found nothing" in a search: return
None, and say so in the type,-> User | None, so the type checker forces callers to handle it. - "Empty result": return an empty list or dict, never
None.for x in resultsthen just works. - "Something went wrong": raise an exception. Returning
Noneor-1for errors is how failures get silently ignored. Errors and Exceptions covers designing those.
Accept general, return specific. Take the broadest input that works (any iterable, not only a list) and return a concrete type the caller can rely on. Type Hints shows how to write that with Iterable[str] and list[str].
# Before: positional flag, mixed return types, None for errors
def load_users(path, active, verbose):
... # returns a list, or None if the file is missing
# After: keyword-only options, one return type, errors raise
def load_users(path: Path, *, active_only: bool = True) -> list[User]:
"""Return users from the file. Raises FileNotFoundError if it is missing."""
...find_orders(customer_id) returns a list of orders, or None when the customer has no orders. What is the best change?Reading signatures at runtime: inspect.signature
inspect.signature(fn) returns a Signature object describing every parameter: its name, its kind (positional-only, keyword-only and so on), its default and its annotation. You seldom need it in application code, but the tools you use every day are built on it. FastAPI reads your endpoint's signature to decide which values come from the path, the query string or the request body. pytest reads a test's parameter names to decide which fixtures to inject. Typer and Click-style CLIs turn parameters into command-line options.
Press Run (⌘ Enter) to see what happens.sig.bind(...) is the useful trick: it applies Python's real argument rules and raises the same TypeError a call would, without running the function. The injector at the end is the core idea of dependency injection by parameter name in about six lines. Two cautions: a decorator that does not use functools.wraps hides the real signature behind (*args, **kwargs), which breaks every tool above, and reading annotations is best done through inspect.signature or annotationlib (3.14) rather than raw __annotations__.
Clamp a value
Write clamp(value, low, high) that returns value if it is between low and high (inclusive), low if it is below, and high if it is above.
clamp(5, 0, 10) → 5
clamp(-3, 0, 10) → 0
clamp(42, 0, 10) → 10You can assume low <= high.
First negative
Write first_negative(nums) that returns the first number below zero, or None if there is none. Stop looking as soon as you find one.
first_negative([3, -1, -4]) → -1
first_negative([1, 2]) → None- parameter vs argument
- A parameter is the name in the
def; an argument is the value passed in the call. - return
- Hands a value back to the caller and ends the function immediately.
- None return
- A function with no
return(or a barereturn) gives backNone. - docstring
- A string as the first statement of a function, shown by
help()and editors. - pure function
- Output depends only on the inputs, and it has no side effects. Easy to test.
- guard clause
- An early
returnthat handles a special case first, keeping the main logic unindented. - function object
- What
defcreates at runtime. It carries__name__,__doc__,__defaults__and more, and can be stored and passed like any value. - command-query separation
- A function either changes state (command, returns
None) or answers a question (query, no side effects), not both. - keyword-only parameter
- A parameter after
*in the signature that callers must pass by name, ideal for flags and options. - inspect.signature
- Returns a
Signaturedescribing a callable's parameters;bind()checks arguments without calling it.