Skip to content

Lesson 11 of 52Functions

Functions

Define functions with def, pass arguments, return values instead of printing them, and write small pure functions.

18 min read0/7 questions

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.

Python
def greet(name): message = f"Hello, {name}!" return message print(greet("Ada"))print(greet("Sam"))
Output
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: name in def greet(name).
  • An argument is the actual value you pass when calling: "Ada" in greet("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.

What happens during area(3, 4)
callerarea()area(3, 4)result = width * heightreturn 12total = 12

The caller passes two arguments. Inside area, the parameters width and height are tied to 3 and 4.

1/4
Python
def area(width, height): result = width * height return result total = area(3, 4)print(total)print(area(2, 5) + area(1, 1))
Output
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.

Python
def add_print(a, b): print(a + b) def add_return(a, b): return a + b x = add_print(2, 3) # shows 5, but gives back Noney = add_return(2, 3) # shows nothing, gives back 5print("x is", x)print("y is", y)
Output
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.

Predict the outputPython

What does this print?

def shout(word):
  print(word.upper())

result = shout("hi")
print(result)
Need a nudge? Hints walk you through it.
Quick check
What does f() return?
def f():
  return 1
  return 2
Need a nudge? A hint rules out a wrong answer.

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.

Python
def stats(nums): return min(nums), max(nums), sum(nums) / len(nums) low, high, mean = stats([4, 8, 15, 16, 23, 42])print(low, high, round(mean, 2))
Output
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.

Python
def to_celsius(fahrenheit: float) -> float: """Convert a temperature from Fahrenheit to Celsius.""" return (fahrenheit - 32) * 5 / 9 print(round(to_celsius(98.6), 1))print(to_celsius.__doc__)
Output
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.

Python
def send_invoice(customer_id: int, amount: float, *, currency: str = "GBP", dry_run: bool = False) -> str: """Email an invoice and return its id.""" return f"INV-{customer_id}" print(send_invoice.__name__, send_invoice.__qualname__, send_invoice.__module__)print(send_invoice.__doc__)print(send_invoice.__defaults__, send_invoice.__kwdefaults__)print(send_invoice.__code__.co_argcount, send_invoice.__code__.co_kwonlyargcount) send_invoice.owner = "billing-team" # you can attach your own attributesprint(send_invoice.owner, type(send_invoice).__name__) handlers = {"invoice": send_invoice} # and store functions like any valueprint(handlers["invoice"](7, 9.99))
Output
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 as Order.total. Decorators that forget to copy them make every log line say wrapper (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, when def runs, 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.

Predict the outputPython

What does this print?

def tag(label, seen=[]):
  seen.append(label)
  return len(seen)

tag("a"); tag("b")
print(tag("c"), tag.__defaults__)
Need a nudge? Hints walk you through it.

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.

Python
def add_tax_pure(prices, rate): return [round(p * (1 + rate), 2) for p in prices] def add_tax_in_place(prices, rate): for i in range(len(prices)): prices[i] = round(prices[i] * (1 + rate), 2) cart = [10.0, 20.0]print(add_tax_pure(cart, 0.2), cart) # cart unchanged add_tax_in_place(cart, 0.2)print(cart) # cart was mutated
Output
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.

Match the pairs0/4 matched

Is each function pure, or does it have a side effect?

Choose an item, then its match on the other side.

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:

Python
nums = [3, 1, 2]result = nums.sort() # a command: sorts in place, returns Noneprint(result, nums) print(sorted([3, 1, 2])) # a query: returns a new list, changes nothing prices = {"tea": 3}prices.update({"jam": 4}) # command: returns Noneprint(prices.get("jam")) # query: no change
Output
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.

Functional core, imperative shell
handle_checkoutshell: reads and writesload_cartI/O: database readapply_discountspureadd_taxpureprice_cartcore: pure querysave_orderI/O: database writesend_receiptI/O: emailroot

The outer function is the shell. It orchestrates, but makes no business decisions itself.

1/3
Predict the outputPython

What does this print?

names = ["sam", "ada"]
names = names.sort()
print(names)
Need a nudge? Hints walk you through it.

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.

Python
def shipping_cost(total: float, country: str) -> float: if total <= 0: return 0.0 if total >= 100: return 0.0 if country != "UK": return 15.0 return 4.99 print(shipping_cost(0, "UK"), shipping_cost(150, "US"), shipping_cost(30, "US"), shipping_cost(30, "UK"))
Output
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".

Put it in order5 steps

Order the lines to make a function that returns the first word longer than 5 letters, or None.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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 results then just works.
  • "Something went wrong": raise an exception. Returning None or -1 for 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."""
    ...
Quick check
A teammate's find_orders(customer_id) returns a list of orders, or None when the customer has no orders. What is the best change?
Need a nudge? A hint rules out a wrong answer.

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.

Python
import inspect def send_invoice(customer_id: int, amount: float, /, note: str = "", *, currency: str = "GBP", dry_run: bool = False) -> str: return f"INV-{customer_id}" sig = inspect.signature(send_invoice)print(sig)for name, p in sig.parameters.items(): default = "required" if p.default is inspect.Parameter.empty else repr(p.default) print(f"{name:<12} {p.kind.name:<22} {default}") bound = sig.bind(42, 9.99, currency="EUR") # check arguments without callingbound.apply_defaults()print(bound.arguments) try: sig.bind(42, 9.99, "x", "EUR")except TypeError as err: print("TypeError:", err) # A tiny pytest-style injector: fill parameters by nameproviders = {"db": lambda: "postgres://primary"} def get_user(user_id: int, db: str) -> str: return f"user {user_id} from {db}" def call_with_deps(fn, **given): kwargs = dict(given) for name in inspect.signature(fn).parameters: if name not in kwargs and name in providers: kwargs[name] = providers[name]() return fn(**kwargs) print(call_with_deps(get_user, user_id=7))
Output
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__.

ChallengeEasy

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)  →  10

You can assume low <= high.

Python
def clamp(value: float, low: float, high: float) -> float: # Return early when value is out of range. pass
ChallengeEasy

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
Python
def first_negative(nums: list[int]) -> int | None: # return inside the loop ends the function right away pass
Key terms
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 bare return) gives back None.
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 return that handles a special case first, keeping the main logic unindented.
function object
What def creates 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 Signature describing a callable's parameters; bind() checks arguments without calling it.