Chapter 3 · 5 levels

Functions

Package store logic into reusable functions with parameters, defaults and return values, then sort and transform data with them.

Start

Every time you copy and paste a calculation and change one number, you’ve found a function waiting to be written. A function gives a name to a piece of logic, takes inputs, and hands back a result. Write it once, test it once, use it everywhere.

At Harbor & Pine the same rules come up again and again: the total of a cart line with a discount, the size band of an order, the price hidden inside a text field like "$1,249.00". In this chapter you’ll turn each of these into a function, learn how default and keyword arguments make functions pleasant to call, return several values at once, and use small lambda functions to sort data the way the business wants it.

Functions also matter for pandas. Many pandas methods accept a function as an argument, and the cleaning code you’ll write in chapter 8 is far easier to trust when each step is a small named function.

Levels

  1. A line-total function with a discount

    from Angela Rivera, Head of Customer Support

    def, return, parameters, default arguments, keyword arguments

    Code Difficulty 2 of 5 Not started

  2. Return an order summary

    from Jennifer Castillo, Support Team Lead

    return, dictionaries, edge cases, len sum

    Code Difficulty 2 of 5 Not started

  3. Tag orders by size

    from Megan Collins, Head of Sales

    functions, if elif else, list comprehension, banding

    Code Difficulty 2 of 5 Not started

  4. Sort products with a key

    from Thomas Whitaker, Head of Merchandising

    sorted, key function, lambda, tie breaking

    Code Difficulty 3 of 5 Not started

  5. Boss: parse the supplier export

    from Laura Bennett, Head of Finance

    functions, string methods, float conversion, f strings, composition

    Boss · 3 steps Difficulty 3 of 5 Not started