Chapter 4

Write and Test Functions

Turn the familiar measurement summary into functions with explicit inputs and results, trace each call, check known cases, and document the behavior a caller can rely on.

The previous chapter classified available readings, skipped missing ones, and carried a total and count to a final mean. Copying that complete calculation for every new dataset would repeat several connected instructions and create several places to repair.

We will first move the familiar code into a named function without changing its calculation. Then the caller will pass readings into `mean(readings)` and receive a result. Tracing two calls will show that each one begins with fresh local work and returns only the value the caller needs.

The completed program will format an available mean or report that it is unavailable. Small tests will check ordinary, one-reading, empty, and all-missing cases against answers worked out independently. Clear names and docstrings will finish the interface before the next chapter develops richer work with ordered values.

After this chapter

  • Distinguish a function definition from a function call.
  • Pass a list of readings into `mean(readings)` and return either its numerical mean or `None` when none are available.
  • Trace argument binding, fresh local total and count values, and the result returned from two separate calls.
  • Use a simple default and keyword argument to make `format_mean` calls readable.
  • Check ordinary and boundary results with independently reasoned expectations and assertions.
  • Write meaningful names and concise docstrings that state caller-visible behavior and special cases.

Lessons

  1. 01
    Extract Familiar Work into a Function

    Give familiar summary code one name, define it before use, and run it through a call.

    3 exercises
  2. 02
    Pass Values and Return a Result

    Pass readings into a function, return a reusable result, and distinguish returning from printing.

    3 exercises
  3. 03
    Trace One Function Call

    Trace parameter binding, fresh local names, two separate calls, and the value returned to each caller.

    3 exercises
  4. 04
    Make Function Calls Clear

    Use a simple default and readable positional or keyword calls without hiding data flow.

    3 exercises
  5. 05
    Check Function Results

    Check public results with known answers, useful failure messages, and distinct boundary cases.

    3 exercises
  6. 06
    Name and Document the Interface

    Document the stable mean and format_mean contracts without narrating their implementation.

    3 exercises

Review and practice

  1. Review

    Review definitions, calls, parameters, returns, local work, defaults, tests, and docstrings.

  2. Exercises

    Practice definitions, calls, local work, returns, defaults, keyword arguments, tests, and docstrings.

Chapter progress