Module 4: Functions, Scope, and Contracts

Functions as Clear Interfaces

Functions as Clear Interfaces

Functions isolate behavior behind named input and output contracts. They reduce duplication, separate decisions, and create units that can be tested without running a whole program.

Module: Module 4: Functions, Scope, and Contracts

Core mental model

This lesson is built around four connected ideas. Read them as a decision framework, then prove each one with the walkthrough.

  • Parameters are inputs, return values are outputs, and mutation or IO are side effects.
  • Keyword-only parameters make option meaning visible at call sites.
  • Mutable default arguments are reused and should be replaced by a None sentinel.
  • Flexible args and kwargs are valuable for forwarding but can hide unclear APIs.

Walkthrough

def summarize(values, *, precision=2):
    if not values:
        raise ValueError("values must not be empty")
    average = sum(values) / len(values)
    return {
        "count": len(values),
        "minimum": min(values),
        "maximum": max(values),
        "average": round(average, precision),
    }

print(summarize([10, 20, 35], precision=1))

The guard states the empty-input contract early. The keyword-only precision documents itself at the call site, and returning data keeps the function independent from printing.

Hands-on lab

Extract validation, aggregation, and formatting from the inventory lab into separate functions. Only the outermost CLI layer should print.

What to watch for

  • A function without explicit return produces None.
  • A catch-all kwargs parameter can hide misspelled options.
  • One function that parses, writes, prints, and aggregates has too many reasons to change.

Engineering checklist

  • Connect the lesson's mental model to the choices made in the walkthrough.
  • Test the normal case, an empty or boundary case, and one invalid case.
  • Keep external input, side effects, and reusable logic in clearly separated layers.
  • Prefer the clearest correct implementation before optimizing or generalizing it.

Completion check

You can implement the lab without copying the example, explain the core concepts in your own words, and show tests or terminal output that demonstrate the expected and failure paths.