Skip to content
Free public beta until December 4, 2026: every course is open, no card needed. After that, the first chapter of each course stays free and full access is a one-time $39 ($19 for up to 100 founding members chosen for helpful feedback). Your progress is kept. How the beta works

Recipe

Turn repeated code into a function

Use when: the same few lines appear in two places, or one block of code does a job you can name

Goal: one small, named, documented, checked function used everywhere the code was

Taught in Designing functions

  1. 1

    Pick the lines that do one job you can name in a sentence without "and".

    Example

    round(price * 1.2, 2), typed in three places: "add 20% tax".

    Why: a function with one clear job is easy to name, check and reuse.

  2. 2

    The values that change between copies become parameters; the value the rest of the code needs becomes the return value.

    Example

    price varies, so it's the parameter; the taxed price is returned.

    Why: parameters and return are the function's whole connection to the outside, with no hidden globals.

  3. 3

    A verb for an action, the value's name for a calculation, a question for yes or no. Add defaults for settings that rarely change.

    Example

    def with_tax(price, rate=0.2):

    Why: a good name makes every call site explain itself.

  4. 4

    One line, as a command, saying what comes back.

    Example

    """Return price with tax added, rounded to cents."""

    Why: help() and your editor show it to everyone who calls the function.

  5. 5

    Write two or three asserts with answers worked out by hand, then swap every copy of the old lines for a call.

    Example

    assert with_tax(10) == 12.0, then total = with_tax(price) in all three places.

    Why: the checks prove the function matches the code it replaces, before anything depends on it.