Skip to content

05. Functions

So far you have written scripts that run from top to bottom. Real data work repeats the same steps: clean a price, compute a mean, check a range. This module turns each step into a function, a named and reusable piece of code. You build a small toolkit of cleaning and metric functions and use it on the course datasets.

  • Define functions with def, pass arguments, return values and know when a function returns None.
  • Use positional and keyword arguments, default values, and the * and / markers for keyword-only and positional-only parameters, with a reason for each.
  • Collect and forward any number of arguments with *args and **kwargs.
  • Predict which variable a name refers to with the LEGB scope rule, and build closures that remember settings or state.
  • Pass functions to other functions: sorted(key=...), min, max, map and filter, with lambda for short keys, and choose between map/filter and comprehensions.
  • Walk nested JSON with recursion and document every function with a Google-style docstring.

Suppose three scripts clean the unit_price column of data/sales_raw.csv. Each script repeats the same four lines. Then the file gets a new missing-value token. You must find and fix all three copies, and you will miss one.

A function gives a name to one step. You write the step once and call it everywhere. A function gives you four things:

  • Reuse: one definition, many calls.
  • One place to fix: a bug fix in the function fixes every caller.
  • Testing: you can check a function on its own with a few known inputs.
  • Readability: a pipeline reads as a list of steps: clean_price, mean, percent_change.

You create a function with a function definition. It starts with the keyword def, then the function name, the parameters in parentheses and a colon. The indented lines under it are the body.

def to_fahrenheit(celsius):
return celsius * 9 / 5 + 32
print(to_fahrenheit(21.7))
print(to_fahrenheit(0))
Output
71.06
32.0
  • celsius is a parameter: a name in the definition that receives a value when the function runs.
  • 21.7 is an argument: the value you pass in the call.
  • return ends the function and sends a value back to the caller. That value is the return value.
  • Python does not run the body when it reads def. It runs the body each time you call the function.
Term Where it appears Example
parameter in the def line celsius
argument in the call 21.7
return value after return celsius * 9 / 5 + 32
signature the name and the parameter list to_fahrenheit(celsius)
flowchart LR
    A["Call<br/>to_fahrenheit(21.7)"] --> P["Parameter<br/>celsius = 21.7"]
    P --> B["Body runs"]
    B --> R["return 71.06"]
    R --> C["Value at the<br/>call site"]

PEP 8 asks for snake_case function names and two blank lines around a top-level def. A good function name is a verb or a verb phrase: clean_price, load_config, count_missing.

return ends the function at once. Code after it in the same branch never runs. A function can return several values. Python packs them into a tuple, and the caller unpacks them:

def min_max(values):
return min(values), max(values)
low, high = min_max([21.0, 21.9, 21.4, 22.9])
print(low, high)
print(min_max([19.5, 20.7]))
Output
21.0 22.9
(19.5, 20.7)

A function without a return statement returns None. This is the most common beginner bug: the function prints a result, and the caller expects to get it back.

def show_mean(values):
print(sum(values) / len(values))
result = show_mean([21.0, 21.9, 21.4])
print(result)
Output
21.433333333333334
None

The first line comes from print() inside the function. The second line shows that result is None. Return values; let the caller decide whether to print them.

A side effect is any change that a function makes outside its own return value: printing, writing a file, or changing a list that the caller passed in. A pure function has no side effects, and its return value depends only on its arguments. to_fahrenheit is pure. Pure functions are easy to test and safe to rerun, so data pipelines are built from them.

A parameter is a new name for the same object that the caller passed (see mutability in module 04). So a function that changes a list argument changes the caller’s list:

def add_offset_in_place(readings, offset):
for i in range(len(readings)):
readings[i] = readings[i] + offset
def add_offset(readings, offset):
return [r + offset for r in readings]
raw = [21.0, 21.9, 21.4]
shifted = add_offset(raw, -0.35)
print(raw, [round(r, 2) for r in shifted])
add_offset_in_place(raw, -0.35)
print([round(r, 2) for r in raw])
Output
[21.0, 21.9, 21.4] [20.65, 21.55, 21.05]
[20.65, 21.55, 21.05]

add_offset builds a new list and leaves raw alone. add_offset_in_place changes raw itself and returns None. Prefer the first form. If a function must change its argument, say so in its name and its docstring, as list.sort() does.

Positional arguments, keyword arguments and defaults

Section titled “Positional arguments, keyword arguments and defaults”

Each line of data/sales.csv has revenue = unit price × quantity × (1 − discount). Most lines have no discount, so the parameter discount gets a default value: the value it takes when the caller passes nothing.

def line_revenue(unit_price, quantity, discount=0.0):
return round(unit_price * quantity * (1 - discount), 2)
print(line_revenue(79.99, 3)) # positional arguments
print(line_revenue(249.00, 1, 0.1)) # all three by position
print(line_revenue(quantity=2, unit_price=89.50)) # keyword arguments, any order
print(line_revenue(249.00, 3, discount=0.1)) # mixed: positional first
Output
239.97
224.1
179.0
672.3
  • A positional argument is matched to a parameter by its position.
  • A keyword argument is matched by name (discount=0.1). Order does not matter, and the call explains itself.
  • In a call, positional arguments come first, then keyword arguments.
  • In a definition, parameters with defaults come after parameters without defaults. This rule does not apply after *: def f(*, digits=1, unit) is valid.

A call with a missing argument fails before the body runs:

print(line_revenue(79.99))
Output
TypeError: line_revenue() missing 1 required positional argument: 'quantity'

Keyword-only and positional-only parameters

Section titled “Keyword-only and positional-only parameters”

Two markers in the parameter list control how callers may pass arguments:

  • Parameters after a bare * are keyword-only: the caller must name them.
  • Parameters before a / are positional-only: the caller must not name them.
def f(pos_only, /, normal, *, kw_only):
───────── ────── ───────
by position either by name

Each marker solves a real problem. Use them on purpose, not by habit.

Marker Use it when Reason Example
* (keyword-only) a parameter is an option or a flag summarize(readings, 2) hides what 2 means; digits=2 says it summarize(readings, *, digits=1)
* (keyword-only) two parameters are easy to swap percent_change(new, old) gives a wrong answer with no error percent_change(*, old, new)
/ (positional-only) the name means nothing to the caller you can rename the parameter later without breaking calls mean(values, /)
/ (positional-only) the function also takes **kwargs any key, even values, can then go into **kwargs tag(values, /, **labels)

Keyword-only options have one more benefit. You can add a new option later, or reorder the options, and no existing call breaks.

Python’s own functions use both markers. The inspect module shows a signature:

import inspect
print(inspect.signature(sorted))
print(inspect.signature(len))
Output
(iterable, /, *, key=None, reverse=False)
(obj, /)

sorted() takes the data by position and the options key and reverse only by name. len() takes its one argument only by position. Here are both rules broken:

def mean(values, /):
return sum(values) / len(values)
print(mean([21.0, 21.9, 21.4]))
print(mean(values=[21.0, 21.9, 21.4]))
Output
21.433333333333334
TypeError: mean() got some positional-only arguments passed as keyword arguments: 'values'
def summarize(readings, *, digits=1):
return round(sum(readings) / len(readings), digits)
print(summarize([21.0, 21.9, 21.4], digits=2))
print(summarize([21.0, 21.9, 21.4], 2))
Output
21.43
TypeError: summarize() takes 1 positional argument but 2 were given

Sometimes a function must accept any number of arguments.

  • A parameter with one star, by convention *args, collects the extra positional arguments into a tuple.
  • A parameter with two stars, by convention **kwargs, collects the extra keyword arguments into a dict.

The names after the stars are free. The stars do the work.

def total_units(*quantities):
print("received:", quantities)
return sum(quantities)
def label(name, **tags):
print("tags:", tags)
return name + " " + " ".join(f"{k}={v}" for k, v in tags.items())
print(total_units(1, 2, 3))
print(total_units())
print(label("S4", status="warn", sensor_type="vibration"))
Output
received: (1, 2, 3)
6
received: ()
0
tags: {'status': 'warn', 'sensor_type': 'vibration'}
S4 status=warn sensor_type=vibration

The same stars work the other way in a call. *sequence unpacks a list or tuple into positional arguments, and **mapping unpacks a dict into keyword arguments:

readings = [21.0, 21.9, 21.4]
print(*readings, sep=" | ")
row = {"unit_price": 249.00, "quantity": 3, "discount": 0.1}
print(line_revenue(**row))
Output
21.0 | 21.9 | 21.4
672.3

line_revenue(**row) is the same call as line_revenue(unit_price=249.00, quantity=3, discount=0.1). The dict keys must match the parameter names.

The main use of **kwargs is forwarding: a function accepts options that it does not use itself and passes them on to another function. Machine learning code does this all the time. The hyperparameters in data/config.json (the settings you choose before you train a model, such as C and max_iter) are a dict, and ** turns them into keyword arguments for the model:

from sklearn.linear_model import LogisticRegression
params = {"C": 1.0, "max_iter": 1000} # config["model"]["params"]
model = LogisticRegression(**params)
print(model.C, model.max_iter)
Output
1.0 1000

All five kinds of parameters can appear in one signature, in this order:

def demo(a, /, b, *args, c, d=4, **kwargs):
print(a, b, args, c, d, kwargs)
demo(1, 2, 3, c=5, e=6)
Output
1 2 (3,) 5 4 {'e': 6}
Kind Syntax Filled by Example in demo
positional-only before / position a
positional-or-keyword between / and * position or name b
var-positional *args extra positions, as a tuple args
keyword-only after * or *args name only c, d
var-keyword **kwargs extra names, as a dict kwargs

A scope is the region of a program where a name is visible. A namespace is the mapping from names to objects in one scope. Each call of a function gets a fresh local namespace. It disappears when the function returns.

  • A local variable is a name assigned inside a function. Only that function sees it.
  • A global variable is a name assigned at the top level of a file (the module). Every function in the file can read it.

When Python meets a name, it looks it up in four scopes, in a fixed order. This is the LEGB rule:

flowchart TD
    N["Python meets the name x"] --> L{"L: Local<br/>assigned in this function?"}
    L -- yes --> UL["use the local x"]
    L -- no --> E{"E: Enclosing<br/>in an outer function?"}
    E -- yes --> UE["use the enclosing x"]
    E -- no --> G{"G: Global<br/>at the top of the file?"}
    G -- yes --> UG["use the global x"]
    G -- no --> B{"B: Built-in<br/>len, sum, print ...?"}
    B -- yes --> UB["use the built-in x"]
    B -- no --> NE["NameError"]
unit = "°C" # global
def make_report(sensor_id):
header = f"Sensor {sensor_id}" # local to make_report, enclosing for line()
def line(value):
# value: local. header: enclosing. unit: global. round: built-in.
return f"{header}: {round(value, 1)} {unit}"
return line(21.66)
print(make_report("S1"))
Output
Sensor S1: 21.7 °C

The enclosing scope is the scope of an outer function, seen from a function defined inside it. The built-in scope holds the names that Python always provides, such as len, sum and print.

Python decides at definition time whether a name is local: any assignment to a name inside a function makes it local in the whole function. So this counter fails, even though a global rejected exists:

rejected = 0
def reject(value):
rejected = rejected + 1
return None
reject("N/A")
Output
UnboundLocalError: cannot access local variable 'rejected' where it is not associated with a value

The line rejected = rejected + 1 makes rejected local. Python then reads the local rejected before it has a value. An UnboundLocalError is the error for this case. Two statements tell Python to use an outer name instead:

Statement Effect Use
global name assignments change the module-level name rarely; prefer returning a value
nonlocal name assignments change name in the enclosing function closures with state (next section)

Assigning to a built-in name shadows it: your name hides the built-in in that scope. After sum = 0, the call sum(values) raises TypeError: 'int' object is not callable. Pick names such as total and lowest instead.

Functions are objects: higher-order functions

Section titled “Functions are objects: higher-order functions”

In Python, a function is an object like a number or a list. You can assign it to another name, store it in a list or dict, pass it as an argument and return it from another function. Languages with this property have first-class functions.

A higher-order function takes a function as an argument or returns one. A function that you pass to another function, so that it calls it later, is a callback.

def apply_steps(value, steps):
for step in steps:
value = step(value)
return value
def collapse_spaces(text):
return " ".join(text.split())
cleaners = [collapse_spaces, str.lower]
print(apply_steps(" Espresso Machine ", cleaners))
print(apply_steps("NON-SLIP yoga MAT", cleaners))
Output
espresso machine
non-slip yoga mat

cleaners holds two functions, not two results: there are no parentheses after the names. str.lower is the method lower of the str type, used as a normal function. collapse_spaces also removes the spaces at both ends, so the pipeline needs no str.strip step. To change the pipeline, you edit a list.

A function defined inside another function can use the variables of the outer function. It keeps them even after the outer function has returned. Such an inner function, together with the outer variables that it remembers, is a closure. The remembered names are its free variables.

def make_range_check(low, high):
def check(value):
return low <= value <= high
return check
temperature_ok = make_range_check(19.0, 23.0) # sensor data sheet
quantity_ok = make_range_check(1, 50) # config.json thresholds
print(temperature_ok(21.7), temperature_ok(44.9))
print(quantity_ok(3), quantity_ok(250))
print(quantity_ok.__code__.co_freevars)
Output
True False
True False
('high', 'low')

make_range_check is a function factory: it builds and returns a new function each time you call it. temperature_ok and quantity_ok share the same code but remember different limits. Use closures to turn settings into ready-to-use functions: a threshold from a config file, a scaling factor, an API key for a client.

A closure can also keep state, a value that survives between calls. It needs nonlocal to change an enclosing variable:

def make_counter():
count = 0
def increment():
nonlocal count
count = count + 1
return count
return increment
count_warning = make_counter()
count_warning()
count_warning()
print(count_warning())
Output
3

Each call of make_counter() creates a new, independent count. Decorators (module 11) are built on closures.

A lambda expression creates a small function without a name. Its body is one expression, and its value is the return value: lambda price: price * 0.9. A lambda cannot contain statements such as if blocks, loops or return.

The main use of a lambda is a key function: a function that sorted(), min() and max() call once on each item to get the value to compare.

stores = [
{"store_id": "S01", "city": "Chicago", "size_sqm": 2850},
{"store_id": "S06", "city": "Miami", "size_sqm": 1680},
{"store_id": "S07", "city": "New York", "size_sqm": 3400},
{"store_id": "S12", "city": "Denver", "size_sqm": 1350},
]
by_size = sorted(stores, key=lambda s: s["size_sqm"], reverse=True)
print([s["city"] for s in by_size])
print(min(stores, key=lambda s: s["size_sqm"])["city"])
print(sorted(["boston", "Chicago", "Atlanta"]))
print(sorted(["boston", "Chicago", "Atlanta"], key=str.lower))
Output
['New York', 'Chicago', 'Miami', 'Denver']
Denver
['Atlanta', 'Chicago', 'boston']
['Atlanta', 'boston', 'Chicago']

Plain sorted() compares character codes, and every uppercase letter comes before every lowercase one. So "boston" lands last. key=str.lower compares lowercase copies but returns the original strings.

Two built-in higher-order functions work on whole sequences:

  • map(function, iterable) calls the function on every item.
  • filter(function, iterable) keeps the items for which the function returns a truthy value.

Both are lazy: they return an iterator, an object that produces the results one at a time when you ask for them. list() asks for all of them. (Module 10 explains iterators.)

raw = ["21.0", "21.9", "21.4", "22.9"]
print(list(map(float, raw)))
print(list(filter(lambda r: r > 21.5, map(float, raw))))
print([float(r) for r in raw if float(r) > 21.5])
Output
[21.0, 21.9, 21.4, 22.9]
[21.9, 22.9]
[21.9, 22.9]

The comprehension does the same job and reads left to right, but it converts each value twice. A comprehension is usually the clearer choice:

Task map / filter Comprehension Prefer
apply an existing function map(float, raw) [float(r) for r in raw] either; map is short
apply an expression map(lambda r: r * 1.8 + 32, c) [r * 1.8 + 32 for r in c] comprehension
keep matching items filter(lambda r: r > 21.5, c) [r for r in c if r > 21.5] comprehension
transform and filter map(f, filter(g, c)) [f(r) for r in c if g(r)] comprehension
stream a huge input once lazy by default use a generator expression (module 10) either

A recursive function calls itself. Recursion fits data that contains smaller copies of itself, such as a JSON document: a dict can hold dicts and lists, which can hold more dicts and lists, to any depth. Each recursive function has two parts:

  • The base case handles the simplest input directly, with no further call. Without it, the function never stops.
  • The recursive case splits the input into smaller parts and calls the function on each part.

This function counts the settings (the non-container values) in part of data/config.json:

def count_settings(obj):
if isinstance(obj, dict): # recursive case: count inside every value
return sum(count_settings(value) for value in obj.values())
return 1 # base case: a number, string, bool or list is one setting
part = {
"output": {"dir": "output/", "format": "csv", "overwrite": False},
"model": {"target": "churned", "params": {"C": 1.0, "max_iter": 1000}},
}
print(count_settings(part))
Output
6

isinstance(obj, dict) returns True when obj is a dict. Each call either returns 1 or adds up the counts of the values one level down:

flowchart TD
    A["count_settings(part) = 6"] --> B["output = 3"]
    A --> C["model = 3"]
    B --> B1["dir: 1"]
    B --> B2["format: 1"]
    B --> B3["overwrite: 1"]
    C --> C1["target: 1"]
    C --> C2["params = 2"]
    C2 --> C3["C: 1"]
    C2 --> C4["max_iter: 1"]

Every call waits on the call stack, the list of calls that have started but not yet returned. Python limits its depth to protect memory. A function with no base case hits the limit and raises a RecursionError:

import sys
print(sys.getrecursionlimit())
def count_down(n):
return count_down(n - 1) # no base case
count_down(3)
Output
1000
RecursionError: maximum recursion depth exceeded

Choose recursion when the depth of the data is unknown: nested JSON, folder trees, HTML documents. Choose a loop for flat sequences. A loop is faster in Python and has no depth limit.

A docstring is a string literal on the first line of a function body. Python stores it on the function, and help(), editors and documentation tools show it. A comment explains a line of code to a maintainer. A docstring explains to a caller what the function does and how to call it.

PEP 257, the docstring convention, asks for:

  • triple double quotes, even for one line;
  • a first line that sums up the function in the imperative mood (“Return the mean.”, not “Returns the mean.”);
  • for longer docstrings, a blank line and then the details.

Three styles exist for the details:

Style Looks like Used by
Google Args:, Returns:, Raises: with indented entries many applications, Google, mkdocstrings sites
NumPy Parameters and Returns headings underlined with ---------- NumPy, pandas, SciPy, scikit-learn
reStructuredText :param x:, :returns: field lists older Sphinx projects

This course uses Google style. It is the most compact of the three, it reads well as plain text in help() and in an editor tooltip, and the documentation-site generators Sphinx (with its napoleon extension) and mkdocstrings render it as HTML. NumPy style is a good choice for large scientific APIs with many parameters. You will read it every day in the NumPy, pandas and scikit-learn documentation, so learn to recognize its headings too.

import inspect
def percent_change(*, old, new):
"""Return the change from old to new, in percent.
Args:
old: The earlier value. Must not be 0.
new: The later value.
Returns:
The relative change in percent: 100 * (new - old) / old.
"""
return (new - old) / old * 100
print(inspect.getdoc(percent_change))
Output
Return the change from old to new, in percent.
Args:
old: The earlier value. Must not be 0.
new: The later value.
Returns:
The relative change in percent: 100 * (new - old) / old.

inspect.getdoc() returns the docstring without its indentation. help(percent_change) shows the signature and the same text in the REPL.

Goal: The unit_price column of data/sales_raw.csv is text such as $79.99, $1,299.00, N/A, - or an empty field. Write one function that turns each value into a float, or into None when the value is missing.

raw_prices = ["$249.00", "$1,299.00", " $79.99 ", "N/A", "-", ""]
print(raw_prices)
print(len(raw_prices), "values")
Output
['$249.00', '$1,299.00', ' $79.99 ', 'N/A', '-', '']
6 values

These are real forms from the file. The value with spaces is defensive: other columns of this file have stray spaces, and a cleaning function should not crash on them. float("$249.00") raises a ValueError, so every value needs cleaning before any arithmetic.

Step 2 — Write the function with a docstring

Section titled “Step 2 — Write the function with a docstring”
MISSING_TOKENS = ("", "N/A", "-")
def clean_price(text):
"""Convert a raw price such as "$1,299.00" to a float.
Args:
text: The raw price text from the CSV file.
Returns:
The price as a float, or None when the text is a missing-value token.
"""
text = text.strip()
if text in MISSING_TOKENS:
return None
return float(text.replace("$", "").replace(",", ""))
print(clean_price("$1,299.00"))
print(clean_price("N/A"))
Output
1299.0
None

The function has two exits. A missing token returns None early, which keeps the main path flat. The other path removes the $ and the thousands separator and converts. MISSING_TOKENS is a tuple in capital letters: PEP 8 writes constants this way.

prices = [clean_price(p) for p in raw_prices]
print(prices)
valid = [p for p in prices if p is not None]
print(f"{len(valid)} valid, {prices.count(None)} missing, max {max(valid):,.2f}")
Output
[249.0, 1299.0, 79.99, None, None, None]
3 valid, 3 missing, max 1,299.00

One call per value, inside a comprehension. The missing values stay visible as None, so you can count them before you decide to drop or fill them.

Step 4 — Make the missing tokens an option

Section titled “Step 4 — Make the missing tokens an option”
def clean_price(text, *, na_values=MISSING_TOKENS):
"""Convert a raw price such as "$1,299.00" to a float.
Args:
text: The raw price text from the CSV file.
na_values: Texts that mean "missing". Defaults to MISSING_TOKENS.
Returns:
The price as a float, or None when the text is in na_values.
"""
text = text.strip()
if text in na_values:
return None
return float(text.replace("$", "").replace(",", ""))
print(clean_price("-"))
print(clean_price("unknown", na_values=("unknown", "")))
print(clean_price(" $14.99", na_values=("unknown", "")))
Output
None
None
14.99

na_values is keyword-only because it is an option: clean_price(raw, ("unknown",)) would hide its meaning. The default is a tuple, which cannot change, so it is a safe default. data/config.json has the same list under cleaning.na_values.

import inspect
print(inspect.signature(clean_price))
print(inspect.getdoc(clean_price).splitlines()[0])
Output
(text, *, na_values=('', 'N/A', '-'))
Convert a raw price such as "$1,299.00" to a float.

The signature shows the keyword-only marker and the default. The first line of the docstring is the summary that editors show in a tooltip.

Common mistakes:

  • Printing the result inside the function instead of returning it. The caller then gets None for every value.
  • Removing $ but not ,. float("1,299.00") raises ValueError: could not convert string to float: '1,299.00'.
  • Returning 0.0 for a missing price. A price of 0 is a real (free) product, and it pulls every mean down. Return None.

Example 2 — Metric functions for a sales report

Section titled “Example 2 — Metric functions for a sales report”

Goal: The six monthly extracts in data/reports/ have these revenue sums for January to June 2024. Write mean and percent_change, and report the month-over-month change.

Step 1 — Write mean with a positional-only parameter

Section titled “Step 1 — Write mean with a positional-only parameter”
monthly = [14162.33, 4719.04, 12296.72, 10879.04, 6675.86, 8533.40]
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
def mean(values, /):
"""Return the arithmetic mean of a non-empty sequence of numbers."""
return sum(values) / len(values)
print(f"Mean monthly revenue: {mean(monthly):,.2f} USD")
Output
Mean monthly revenue: 9,544.40 USD

The name values tells a caller nothing that the position does not. The / keeps it private: you can rename it to numbers tomorrow, and no call breaks. Built-ins such as len() and sum() do the same.

Step 2 — Write percent_change with keyword-only parameters

Section titled “Step 2 — Write percent_change with keyword-only parameters”

The relative change from an old value to a new value is:

change %=new−oldold×100\text{change \%} = \frac{\text{new} - \text{old}}{\text{old}} \times 100
def percent_change(*, old, new):
"""Return the change from old to new, in percent."""
return (new - old) / old * 100
year = percent_change(old=1_645_589.59, new=1_950_934.24) # 2023 -> 2024
print(f"Revenue 2023 -> 2024: {year:+.1f}%")
Output
Revenue 2023 -> 2024: +18.6%

The two parameters have no defaults, but they are still keyword-only. The reason is safety: old and new are both numbers, so a swapped call gives a wrong answer and no error. Named arguments make the direction explicit at every call site.

Step 3 — See the error that protects you

Section titled “Step 3 — See the error that protects you”
print(percent_change(1_950_934.24, 1_645_589.59))
Output
TypeError: percent_change() takes 0 positional arguments but 2 were given

With plain parameters, this call would print -15.7%, a fall in revenue that never happened. The * turns a silent wrong answer into a loud error.

Step 4 — Compute the month-over-month changes

Section titled “Step 4 — Compute the month-over-month changes”
changes = [percent_change(old=a, new=b) for a, b in zip(monthly, monthly[1:])]
for month, change in zip(months[1:], changes):
print(f"{month}: {change:+7.1f}%")
Output
Feb: -66.7%
Mar: +160.6%
Apr: -11.5%
May: -38.6%
Jun: +27.8%

zip(monthly, monthly[1:]) pairs each month with the next one. The function stays small and the loop stays readable, because each line does one job. February fell by two thirds: these are small samples, so one big Electronics order moves a month a lot.

best = max(changes)
best_month = months[changes.index(best) + 1]
print(f"Best month: {best_month} ({best:+.1f}%)")
print(f"Jan -> Jun: {percent_change(old=monthly[0], new=monthly[-1]):+.1f}%")
Output
Best month: Mar (+160.6%)
Jan -> Jun: -39.7%

Small functions combine like building blocks. Report the overall change from the first to the last month, not the mean of the monthly changes. The mean of percent changes is +14.3% here, although revenue fell: a +160% month and a −67% month do not cancel out.

Common mistakes:

  • Calling mean([]). It raises ZeroDivisionError: division by zero. Check for empty input first; module 06 shows how to raise a clear error instead.
  • Dividing by new instead of old. The base of a percent change is always the old value.
  • Writing percent_change(old=b, new=a) in the loop. Keywords make the call readable, but they cannot read your mind. Check one value by hand.

Example 3 — Summarize readings and forward options

Section titled “Example 3 — Summarize readings and forward options”

Goal: Lines 37 to 42 of data/readings.txt are one hour of a server-room sensor. Write summarize(readings, *, digits=1), then a report function that forwards formatting options to it with **kwargs.

def summarize(readings, *, digits=1):
"""Summarize numeric readings.
Args:
readings: A non-empty list of numbers.
digits: Decimal places for the rounded statistics.
Returns:
A dict with the count, min, max, range and mean.
"""
lowest, highest = min(readings), max(readings)
return {
"count": len(readings),
"min": round(lowest, digits),
"max": round(highest, digits),
"range": round(highest - lowest, digits),
"mean": round(sum(readings) / len(readings), digits),
}
shift = [19.5, 20.7, 20.1, 21.2, 21.2, 20.8]
print(summarize(shift))
Output
{'count': 6, 'min': 19.5, 'max': 21.2, 'range': 1.7, 'mean': 20.6}

A dict is a good return value for several named results: the caller picks what it needs by key. The function rounds only at the end, so the range uses the exact min and max.

print(summarize(shift, digits=3))
Output
{'count': 6, 'min': 19.5, 'max': 21.2, 'range': 1.7, 'mean': 20.583}

With digits=3, the mean shows 20.583 instead of 20.6. The call reads like a sentence, because digits must be named.

def sensor_report(sensor_id, readings, **summary_options):
"""Return a one-line report; extra keyword arguments go to summarize()."""
stats = summarize(readings, **summary_options)
return (
f"{sensor_id}: n={stats['count']} mean={stats['mean']} "
f"range={stats['min']}-{stats['max']}"
)
print(sensor_report("S1", shift))
print(sensor_report("S1", shift, digits=2))
Output
S1: n=6 mean=20.6 range=19.5-21.2
S1: n=6 mean=20.58 range=19.5-21.2

sensor_report does not know about digits. It collects every extra keyword into summary_options and passes them on. If summarize gets a new option next month, sensor_report supports it with no change.

Step 4 — Pass options from a dict, and catch a typo

Section titled “Step 4 — Pass options from a dict, and catch a typo”
options = {"digits": 2}
print(sensor_report("S1", shift, **options))
print(sensor_report("S1", shift, digit=2))
Output
S1: n=6 mean=20.58 range=19.5-21.2
TypeError: summarize() got an unexpected keyword argument 'digit'. Did you mean 'digits'?

A dict of options, for example loaded from a config file, unpacks into keyword arguments. Forwarding does not hide mistakes: the misspelled digit reaches summarize, which rejects it and names it. The hint Did you mean 'digits'? appears from Python 3.13 on; Python 3.12 prints the same message without it.

Common mistakes:

  • Forwarding summary_options without the stars: summarize(readings, summary_options). The dict becomes a second positional argument, and Python raises TypeError: summarize() takes 1 positional argument but 2 were given.
  • Rounding before computing the range. Round once, at the end.
  • Accepting **kwargs and then ignoring them. Every option the caller passes must reach a function that uses it, or the caller’s setting is lost with no warning.

Example 4 — Configurable checks with closures

Section titled “Example 4 — Configurable checks with closures”

Goal: data/config.json sets the valid quantity range for a sales line. Build the check from the config, run it on raw quantities from data/sales_raw.csv, and count the rejected lines with a closure.

import json
with open("data/config.json", encoding="utf-8") as f:
config = json.load(f)
thresholds = config["thresholds"]
for name, value in thresholds.items():
print(f"{name:<22} {value}")
Output
min_quantity 1
max_quantity 50
max_discount 0.2
max_missing_fraction 0.05
churn_probability 0.5

json.load() turns the file into nested dicts and lists. Module 07 explains open, with and json in full. Here you need only the result: a dict.

Step 2 — Build a check function from the config

Section titled “Step 2 — Build a check function from the config”
def make_range_check(low, high):
"""Return a function that tests low <= value <= high."""
def check(value):
return low <= value <= high
return check
quantity_ok = make_range_check(thresholds["min_quantity"], thresholds["max_quantity"])
print(quantity_ok(3), quantity_ok(0), quantity_ok(50), quantity_ok(250))
Output
True False True False

quantity_ok is a closure. It remembers low=1 and high=50. Callers need only the value, so the check plugs into any code that expects a one-argument function.

Step 3 — Apply the check to raw quantities

Section titled “Step 3 — Apply the check to raw quantities”
raw_quantities = [1, 2, -3, 4, 250, 1, 999, 25, -1]
kept = list(filter(quantity_ok, raw_quantities))
print("kept:", kept)
print("rejected:", [q for q in raw_quantities if not quantity_ok(q)])
Output
kept: [1, 2, 4, 1, 25]
rejected: [-3, 250, 999, -1]

The negative and absurd quantities are the injected problems of sales_raw.csv. The check is a normal function, so filter() and a comprehension can both use it.

Step 4 — Count rejections with a stateful closure

Section titled “Step 4 — Count rejections with a stateful closure”
def make_counter():
"""Return a function that adds 1 to a private count and returns it."""
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
count_rejected = make_counter()
for q in raw_quantities:
if not quantity_ok(q):
print(f"reject #{count_rejected()}: quantity {q}")
Output
reject #1: quantity -3
reject #2: quantity 250
reject #3: quantity 999
reject #4: quantity -1

nonlocal count lets increment change the count of make_counter. The count survives between calls, so each rejection gets the next number. No global variable is involved, so two counters (for example one per store) never mix.

print(quantity_ok.__code__.co_freevars)
print([cell.cell_contents for cell in quantity_ok.__closure__])
Output
('high', 'low')
[50, 1]

The free variables are stored in cells attached to the function, here high and low in alphabetical order. You rarely need this in real code, but it shows that a closure is ordinary data, not magic.

Common mistakes:

  • Writing return check() instead of return check. The parentheses call the inner function at once and raise TypeError: ... missing 1 required positional argument: 'value'.
  • Forgetting nonlocal. count += 1 then raises UnboundLocalError.
  • Building checks in a loop with lambda v: v <= limit. All the lambdas share the last limit. Use a factory such as make_range_check, which gives each check its own scope (module 13 explains this “late binding”).

Example 5 — Rank products with sorted and key functions

Section titled “Example 5 — Rank products with sorted and key functions”

Goal: Rank eight products from data/products.csv by their margin rate, the share of the price that the shop keeps: (price − cost) / price.

products = [
{"id": "P001", "name": "Wireless Earbuds", "category": "Electronics",
"cost": 31.50, "price": 79.99},
{"id": "P003", "name": "55-inch 4K Smart TV", "category": "Electronics",
"cost": 845.00, "price": 1299.00},
{"id": "P005", "name": "Smartwatch Series 5", "category": "Electronics",
"cost": 88.00, "price": 199.99},
{"id": "P008", "name": "Chef's Knife Set", "category": "Home",
"cost": 48.00, "price": 129.95},
{"id": "P010", "name": "Cotton Bed Sheet Set", "category": "Home",
"cost": 24.00, "price": 69.99},
{"id": "P014", "name": "Running Socks 3-Pack", "category": "Clothing",
"cost": 4.20, "price": 14.99},
{"id": "P015", "name": "Organic Cotton T-Shirt", "category": "Clothing",
"cost": 6.10, "price": 19.99},
{"id": "P026", "name": "Vitamin C Face Serum", "category": "Beauty",
"cost": 6.30, "price": 24.99},
]
print(len(products), "products")
Output
8 products

Each product is a dict with the columns of the file, renamed for short lines. A list of dicts is the plain-Python form of a table.

by_price = sorted(products, key=lambda p: p["price"])
print([p["id"] for p in by_price])
Output
['P014', 'P015', 'P026', 'P010', 'P001', 'P008', 'P005', 'P003']

sorted() calls the lambda once per product and compares the prices. It returns a new list and leaves products unchanged. Dicts cannot be compared with <, so without a key, sorting them raises a TypeError.

def margin_rate(product):
"""Return the share of the price that the shop keeps, from 0 to 1."""
return (product["price"] - product["cost"]) / product["price"]
for p in sorted(products, key=margin_rate, reverse=True)[:3]:
print(f"{p['name']:<24} {margin_rate(p):.1%}")
Output
Vitamin C Face Serum 74.8%
Running Socks 3-Pack 72.0%
Organic Cotton T-Shirt 69.5%

The margin needs a formula and a docstring, so it gets a def. You pass the function itself, key=margin_rate, without parentheses. Cheap beauty and clothing items keep the highest share of their price.

ranked = sorted(products, key=lambda p: (p["category"], -p["price"]))
for p in ranked:
print(f"{p['category']:<12} {p['price']:>8.2f} {p['name']}")
Output
Beauty 24.99 Vitamin C Face Serum
Clothing 19.99 Organic Cotton T-Shirt
Clothing 14.99 Running Socks 3-Pack
Electronics 1299.00 55-inch 4K Smart TV
Electronics 199.99 Smartwatch Series 5
Electronics 79.99 Wireless Earbuds
Home 129.95 Chef's Knife Set
Home 69.99 Cotton Bed Sheet Set

A key that returns a tuple sorts by the first item, then by the second for ties. The minus sign sorts prices from high to low inside each category, while the categories stay A to Z.

best = max(products, key=margin_rate)
worst = min(products, key=margin_rate)
print(f"best: {best['name']} ({margin_rate(best):.1%})")
print(f"worst: {worst['name']} ({margin_rate(worst):.1%})")
Output
best: Vitamin C Face Serum (74.8%)
worst: 55-inch 4K Smart TV (34.9%)

max() and min() take the same key argument. They return the whole item, not the key value, so you keep the name and the id.

Common mistakes:

  • Writing key=margin_rate(p) or key=margin_rate(). The key must be the function itself.
  • Using products.sort(...) and printing its result. list.sort() sorts in place and returns None.
  • Writing -p["category"] to reverse text. The minus sign works only on numbers. Use reverse=True for the whole key, or sort twice: sorted() is stable, so items with equal keys keep their order. Sort by the second key first, then by the first key with reverse=True.

Example 6 — Parse a readings file: map, filter or a comprehension

Section titled “Example 6 — Parse a readings file: map, filter or a comprehension”

Goal: data/readings.txt has 43 lines, one temperature per line. Three lines are broken (error, an empty line and n/a). Keep the valid readings and compute their mean.

from pathlib import Path
lines = Path("data/readings.txt").read_text(encoding="utf-8").splitlines()
print(len(lines), lines[:3], lines[11], repr(lines[23]), lines[34])
Output
43 ['21.0', '21.9', '21.4'] error '' n/a

Path(...).read_text() reads the whole file as one string, and splitlines() splits it into a list of lines. Module 07 covers reading files. Every line is still text.

def is_number(text):
"""Return True if text looks like a decimal number, such as "21.7" or "-3"."""
digits = text.strip().removeprefix("-").replace(".", "", 1)
return digits.isdecimal()
print([is_number(t) for t in ["21.7", "-3", "error", "", "n/a", "1.2.3"]])
Output
[True, True, False, False, False, False]

A predicate is a function that returns True or False. This one removes one minus sign and one decimal point, then asks with isdecimal() if only digits that float() can read remain (isdigit() would also accept "²", and the empty line fails because "".isdecimal() is False). Module 06 shows the other way: try float() and catch the ValueError.

valid = list(map(float, filter(is_number, lines)))
print(len(valid), valid[:5])
print(f"mean {sum(valid) / len(valid):.2f} °C")
Output
40 [21.0, 21.9, 21.4, 21.7, 22.1]
mean 21.06 °C

Read the line from the inside out: filter keeps the number-like lines, and map converts each one with float. Both take existing named functions, so no lambda is needed, which is where map and filter are at their best.

Step 4 — Write the same with a comprehension

Section titled “Step 4 — Write the same with a comprehension”
valid_2 = [float(t) for t in lines if is_number(t)]
print(valid_2 == valid)
print([t for t in lines if not is_number(t)])
Output
True
['error', '', 'n/a']

The comprehension reads left to right and gives the same list. The second line lists the rejected lines, a cheap data-quality check. Most Python teams prefer the comprehension form.

cleaned = [21.0, 0.0, None, 19.5, None, 0.0]
print(list(filter(None, cleaned)))
print([v for v in cleaned if v is not None])
Output
[21.0, 19.5]
[21.0, 0.0, 19.5, 0.0]

filter(None, ...) keeps only truthy items, so it drops the real readings of 0.0 °C along with the None values. Test for the thing you mean: is not None.

converted = map(float, ["21.0", "21.9"])
print(type(converted).__name__)
print(list(converted))
print(list(converted))
Output
map
[21.0, 21.9]
[]

A map object computes its values only when asked, and only once. The second list() finds it empty. Store the result in a list if you need it twice.

Common mistakes:

  • Printing a map or filter object directly. You see <map object at 0x...>, not the values. Wrap it in list().
  • Using filter(None, ...) to drop missing values. It also drops 0, 0.0 and "".
  • Converting with float() before filtering. The first broken line raises a ValueError.

Example 7 — Walk nested JSON with recursion

Section titled “Example 7 — Walk nested JSON with recursion”

Goal: data/config.json and data/customers.json are nested several levels deep. Write recursive functions that list every setting as a dotted path and collect every value of one key at any depth.

print(len(config), "top-level keys:", list(config)[:5], "...")
print(config["project"], config["model"]["params"])
Output
11 top-level keys: ['project', 'version', 'input', 'output', 'columns'] ...
sales-pipeline {'C': 1.0, 'max_iter': 1000}

config is the dict from Example 4. Some values are plain ("project"), and some are dicts that hold more dicts ("model" holds "params"). The depth differs from key to key, which is the sign that recursion fits.

Step 2 — Flatten the config to dotted paths

Section titled “Step 2 — Flatten the config to dotted paths”
def flatten(obj, prefix=""):
"""Return a dict that maps dotted paths such as "model.params.C" to values.
Args:
obj: A value from parsed JSON. Dicts are walked; anything else is a leaf.
prefix: The path of obj inside the whole document.
Returns:
A flat dict of path -> leaf value.
"""
if not isinstance(obj, dict): # base case: a leaf value
return {prefix: obj}
flat = {}
for key, value in obj.items(): # recursive case: one call per child
path = f"{prefix}.{key}" if prefix else key
flat.update(flatten(value, path))
return flat
settings = flatten(config)
print(len(settings), "settings")
for path, value in settings.items():
if path.startswith(("thresholds.", "model.")):
print(f"{path:<32} {value!r}")
Output
31 settings
thresholds.min_quantity 1
thresholds.max_quantity 50
thresholds.max_discount 0.2
thresholds.max_missing_fraction 0.05
thresholds.churn_probability 0.5
model.type 'logistic_regression'
model.target 'churned'
model.test_size 0.25
model.random_state 42
model.params.C 1.0
model.params.max_iter 1000

Each call handles one level: a leaf returns a one-entry dict, and a dict merges the flat dicts of its children with update(). The prefix parameter carries the path down the levels; its default "" means “the top”. Many tools name settings with such flat paths, for example model.params.C on a command line.

def find_values(obj, key):
"""Return every value stored under key, at any depth of dicts and lists."""
found = []
if isinstance(obj, dict):
for k, value in obj.items():
if k == key:
found.append(value)
found.extend(find_values(value, key))
elif isinstance(obj, list):
for item in obj:
found.extend(find_values(item, key))
return found
with open("data/customers.json", encoding="utf-8") as f:
customers = json.load(f)
amounts = find_values(customers, "amount")
print(len(amounts), "orders", f"total {sum(amounts):,.2f} USD")
print(find_values(config, "C"), find_values(customers, "postal_code")[:3])
Output
48 orders total 13,711.70 USD
[1.0] ['81790', '62260', '45915']

This version walks both dicts and lists, because customers.json stores the customers and their orders in lists. It finds all 48 order amounts without knowing where they live. The same function works on both files, which shows the strength of recursion on unknown shapes.

def depth(obj):
"""Return how many levels of dicts and lists obj has (0 for a leaf)."""
if isinstance(obj, dict):
return 1 + max((depth(v) for v in obj.values()), default=0)
if isinstance(obj, list):
return 1 + max((depth(v) for v in obj), default=0)
return 0
print("config depth:", depth(config))
print("customers depth:", depth(customers))
Output
config depth: 3
customers depth: 5

The depth of a container is one more than the depth of its deepest child. max(..., default=0) handles empty dicts and lists, such as the three customers with no orders. The customers file is 5 levels deep: the wrapper dict, the customers list, a customer dict, its orders list and an order dict.

Common mistakes:

  • Forgetting to use the return value of the recursive call. flatten(value, path) alone computes the child’s paths and throws them away.
  • Writing a base case that never matches, for example if obj is None:. The function then recurses until RecursionError.
  • Using a mutable default such as def find_values(obj, key, found=[]). The list survives between top-level calls and mixes the results of different files.
Mistake Symptom Fix
print() instead of return in a function The caller gets None; TypeError with NoneType later Return the value; print at the call site
Code after return in the same block It never runs Move it before the return
return inside the loop of a sum Only the first item is counted Return after the loop ends
A list or dict as a default value: def f(x, seen=[]) Values from earlier calls appear Default to None; create the list in the body
Option passed by position: summarize(r, 2) Unclear calls; later option changes break callers Make options keyword-only with *
Two same-type parameters swapped: percent_change(new, old) A wrong number with no error Make them keyword-only and name them in every call
Assigning to a global name inside a function UnboundLocalError: cannot access local variable Return the new value, or use nonlocal in a closure
A variable named sum, max, list or type TypeError: 'int' object is not callable Rename: total, highest, items
key=margin_rate() TypeError: ... missing 1 required positional argument Pass the function: key=margin_rate
result = values.sort() result is None Use sorted(values) for a new list
print(map(float, raw)) <map object at 0x...> print(list(map(float, raw)))
Reusing a map or filter result The second use is empty Store list(map(...)) once
filter(None, values) to drop missing values Real zeros disappear [v for v in values if v is not None]
A recursive function without a reachable base case RecursionError: maximum recursion depth exceeded Handle the simplest input first, with no call
Forwarding with f(options) instead of f(**options) TypeError: ... takes 1 positional argument but 2 were given Unpack: f(**options)
name = lambda x: ... ruff E731; tracebacks show <lambda> Use def
  • Web development: a web framework calls your view functions with keyword arguments taken from the URL, such as get_order(order_id="O000614"). Keyword-only options are the norm in library APIs.
  • Automation: a cleanup script sorts files with sorted(paths, key=lambda p: p.stat().st_mtime) and deletes the oldest. key= is the same idea as ranking products.
  • Tooling: wrapper functions forward *args, **kwargs to the function they wrap. Logging, retry and timing decorators (module 11) all do this, and closures hold their settings.
  • Recursion everywhere: walking a folder tree, an HTML page or a JSON API response uses the same base-case and recursive-case shape as flatten.
  • def name(parameters): defines a function. A call runs its body. return sends a value back; with no return, the result is None.
  • Prefer pure functions: the result depends only on the arguments, and nothing outside changes.
  • Arguments match parameters by position or by name. Defaults make parameters optional. Never use a mutable default.
  • * makes the parameters after it keyword-only: use it for options and for parameters that are easy to swap. / makes the parameters before it positional-only: use it when the name means nothing to the caller.
  • *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dict. In a call, * and ** unpack. Use **kwargs to forward options.
  • Python looks a name up in the Local, Enclosing, Global and Built-in scopes, in that order. An assignment makes a name local to the whole function.
  • Functions are objects. Pass them to sorted, min, max, map and filter. A closure is an inner function that remembers its enclosing variables; nonlocal lets it change them.
  • Use lambda only for short inline keys. Prefer comprehensions to map/filter with a lambda.
  • A recursive function needs a base case and a recursive case. It fits nested data such as JSON.
  • Document every function with a docstring. This course uses Google style: a one-line summary, then Args: and Returns:.

Q1. What is the difference between a parameter and an argument?

Answer

A parameter is the name in the def line, such as celsius. An argument is the value passed in a call, such as 21.7. When the function runs, the parameter refers to the argument.

Q2. A function computes a mean and prints it but has no return statement. What does x = f([1, 2, 3]) store in x?

Answer

None. The function prints 2.0, but a function without return returns None. Return the mean instead, and print it at the call site if you need to see it.

Q3. Why is def add_tag(tag, tags=[]) a bug, and how do you fix it?

Answer

Python creates the default list once, when it runs the def line. Every call that uses the default appends to that same list, so tags from earlier calls leak into later calls. Write def add_tag(tag, tags=None): and start the body with if tags is None: tags = [].

Q4. Give one reason to make a parameter keyword-only and one reason to make a parameter positional-only.

Answer

Keyword-only (*): the parameter is an option, such as digits=2, so the name explains the call, and you can add or reorder options later without breaking callers. It also protects two same-type parameters, such as old and new, from being swapped. Positional-only (/): the name means nothing to the caller, such as values in mean(values, /), so you keep the freedom to rename it.

Q5. Inside def report(name, **options), what is the type of options after the call report("S1", digits=2, unit="°C"), and what does it contain?

Answer

A dict: {'digits': 2, 'unit': '°C'}. **options collects every keyword argument that does not match another parameter.

Q6. What does LEGB stand for, and in what order does Python search?

Answer

Local, Enclosing, Global, Built-in, in that order. Python uses the first scope that has the name. If none has it, Python raises a NameError.

Q7. Why does this raise UnboundLocalError?

total = 0
def add(x):
total = total + x
return total
Answer

The assignment total = ... makes total a local name in the whole function. The right side then reads the local total before it has a value. Pass the total in and return the new total, or, in a closure, declare nonlocal total.

Q8. What is a closure? Give a data use.

Answer

A closure is an inner function that remembers the variables of the function that created it, even after that function has returned. A data use: make_range_check(1, 50) returns a check that remembers the quantity limits from a config file, so callers pass only the value.

Q9. How do you sort a list of product dicts by category A to Z, then by price from high to low?

Answer

sorted(products, key=lambda p: (p["category"], -p["price"])). The tuple key sorts by category first and by the negative price for ties, which puts high prices first.

Q10. When is map(float, raw) a fine choice, and when is a comprehension better?

Answer

map is fine when you apply an existing named function, such as float, to every item. A comprehension is better when you would need a lambda, or when you transform and filter in one step: [float(t) for t in raw if is_number(t)]. Remember that map returns a lazy iterator that you can use only once.

Q11. What two parts does every recursive function need? What happens if the second one is missing?

Answer

A base case, which returns a result directly, and a recursive case, which calls the function on a smaller part. Without a base case that the input eventually reaches, the calls never stop, and Python raises RecursionError: maximum recursion depth exceeded after about 1,000 nested calls.

Q12. Which docstring style does this course use, and what are its main sections?

Answer

Google style. A one-line summary in the imperative mood, a blank line, then the sections Args:, Returns: and, when the function raises errors on purpose, Raises:. Each entry is indented under its section.

Your progress

0 / 4 done

  • Exercises: 25 exercises with hints and full solutions, from warm-up to challenge.
  • Mini-project: build a reusable toolkit of functions and use it to report on nested customer records.
  • Cheat sheet: every parameter kind, scope rule and higher-order pattern of this module on one page.
  • Next module: 06. Errors and debugging teaches you to read tracebacks, raise and catch exceptions and debug with breakpoint().