Chapter 3 · 5 levels
Functions
Package store logic into reusable functions with parameters, defaults and return values, then sort and transform data with them.
StartEvery 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
- A line-total function with a discount
from Angela Rivera, Head of Customer Support
def, return, parameters, default arguments, keyword arguments
- Return an order summary
from Jennifer Castillo, Support Team Lead
return, dictionaries, edge cases, len sum
- Tag orders by size
from Megan Collins, Head of Sales
functions, if elif else, list comprehension, banding
- Sort products with a key
from Thomas Whitaker, Head of Merchandising
sorted, key function, lambda, tie breaking
- Boss: parse the supplier export
from Laura Bennett, Head of Finance
functions, string methods, float conversion, f strings, composition