Python, NumPy & pandas · Lesson 9

Functions and Modules

Functions and Modules concerns reusable Python functions.

ConceptWorked examplePracticeKnowledge check
Textbook walkthrough

What Functions and Modules actually means

Functions and Modules concerns reusable Python functions. A function packages a sequence of statements behind a name, receives inputs through parameters and can return an output. Functions create local scope and are first-class objects, so they can be stored, passed and composed.

Functions and Modules matters because numerical arrays and labelled tables are the working representations for most data-science pipelines. Types, shape, alignment, missingness and reusable code determine whether later statistics and models receive the intended data.

Deeper walkthrough

Read Functions and Modules as a mechanism, not a recipe

Treat this as a sequence of observable decisions rather than one opaque command. Stage 1: Define the function with def (or a lambda for a small expression). Stage 2: Bind supplied arguments to parameters when the function is called. Stage 3: Execute the indented function body in a local scope. Final checkpoint: Use docstrings and type hints to communicate intent; use *args/**kwargs only when variable argument structure is genuinely useful.

Mechanism

Follow the transformation

Define the function with def (or a lambda for a small expression).

Bind supplied arguments to parameters when the function is called.

Execute the indented function body in a local scope.

Evidence

Know what would convince you

  • Compare row/column counts, dtypes and missing values before and after the operation.
  • Trace a few representative rows or one group manually from source values to result.
Useful distinctionparameter: Name in the function definition.
Visual demonstration of Functions and Modules
Visual demonstration: use the diagram to trace the main objects and state changes involved in Functions and Modules.
Click a stage to inspect what happens, what changes, and what should be checked before moving on.
Stage 1

Define the function with def (or…

Define the function with def (or a lambda for a small expression). This is an input-preparation stage for Functions and Modules. Verify the relevant type, shape, units, keys, missingness or assumptions before later steps depend on them.

Input focus: confirm the data/object, units, type, shape and assumptions before the next operation depends on them.
How it works

Trace the mechanism step by step

  1. Define the function with def (or a lambda for a small expression).
  2. Bind supplied arguments to parameters when the function is called.
  3. Execute the indented function body in a local scope.
  4. return sends a value back to the caller and stops that call; without an explicit return, the result is None.
  5. Use docstrings and type hints to communicate intent; use *args/**kwargs only when variable argument structure is genuinely useful.
Worked demonstration

Make the concept concrete

Demonstration

Python example

# Step 1 — Define the reusable `kpi_rate` function; its indented body describes what happens for each call.
def kpi_rate(successes: int, total: int = 100) -> float:
    # Step 2 — Execute this statement and inspect how it changes the current value, object or program state.
    """Return success percentage; reject impossible denominators."""
    # Step 3 — Evaluate this condition and execute the indented branch only when the condition is true.
    if total <= 0:
        # Step 4 — Raise an explicit exception to signal that the required condition or input contract was violated.
        raise ValueError("total must be positive")
    # Step 5 — Return the computed value to the caller so the result can be reused or tested.
    return 100 * successes / total

# Step 6 — Display the current value explicitly so the result/state can be inspected during execution.
print(kpi_rate(42, 60))
# Step 7 — Display the current value explicitly so the result/state can be inspected during execution.
print(kpi_rate(successes=75))
Expected / illustrative result
70.0
75.0
Interpret the result.

For Functions and Modules, trace representative source rows/columns into the result and reconcile row counts, dtypes, keys or missing values that the operation could change.

Distinctions & related ideas

Know what this is — and what it is not

parameterName in the function definition.
argumentValue supplied at a call site.
returnValue sent back to the caller.
yieldProduces a sequence lazily from a generator, pausing function state between values.
Use deliberately

When it is appropriate

Use Functions and Modules when the data are naturally tabular and row grain, column meaning, keys and dtypes can be stated explicitly.

Boundary conditions

When to stop or reconsider

Reconsider the operation if row identity/grain is unclear, join keys are not validated, chained transformations hide state, or the task is better expressed with a simpler table operation.

Common mistakes

Failure modes to recognise

  • Changing row grain or row count without noticing it.
  • Joining/grouping on keys whose uniqueness or missingness was never checked.
  • Interpreting a derived column or aggregation without reconciling it to source rows and units.
Verification

How to check the result

  • Compare row/column counts, dtypes and missing values before and after the operation.
  • Trace a few representative rows or one group manually from source values to result.
  • For joins/reshapes/grouping, verify key uniqueness/cardinality and reconcile totals where totals should be preserved.
Hands-on practice

Demonstrate understanding

Try this:

Build a tiny, inspectable example of Functions and Modules. First define the function with def (or a lambda for a small expression). Then bind supplied arguments to parameters when the function is called. Write the expected result before running it, and explain one condition that would make the result misleading or invalid.

Work with 4–8 rows that contain the exact key/category/missing-value pattern you want to understand. Trace one row or group all the way through.
Knowledge check

Check reasoning, not memorisation

Before trusting a result from Functions and Modules, which check provides the strongest evidence that you understand and applied it correctly?

Quick reference

Keep the important distinctions visible

Step 1Define the function with def (or a lambda for a small expression).
Step 2Bind supplied arguments to parameters when the function is called.
Step 3Execute the indented function body in a local scope.
Step 4return sends a value back to the caller and stops that call; without an explicit return, the result is None.
Lesson summary

What to remember

  • Functions and Modules concerns reusable Python functions. A function packages a sequence of statements behind a name, receives inputs through parameters and can return an output. Functions create local scope and are first-class objects, so they can be stored, passed and composed.
  • Define the function with def (or a lambda for a small expression).
  • Changing row grain or row count without noticing it.
  • Compare row/column counts, dtypes and missing values before and after the operation.