Using Functions
A track of P41 · Functions & Reuse.
Call built-in tools like len and sorted, then write your own two-line function — naming work so you can reuse it.
A function is a tool with a slot on each side: you put a value in, some named
work happens, and a value comes out. You have been using them since your very
first cell — len(words) took a list and handed back a count, sorted(words)
took the same list and handed back an ordered copy. The first module simply
gives you the name for what you were already doing, and a feel for the
in-and-out rhythm you can rely on with any tool you meet.
Picture this morning's version of a familiar chore. You have a list of two
hundred terms pulled from a transcript, and someone asks how many there are.
You could count them — carefully, twice, because you lost your place the first
time. Or you type len(terms), press run, and the number is simply there.
Want them in alphabetical order too? sorted(terms). The total character
count of a title? Ask for it by name. Once you notice that the notebook's
tools all work this way — hand something in, get something back — a better
question starts to itch: the chores nobody wrote a tool for, the ones specific
to your desk — who writes those?
You do, and it takes two lines. That is the second module: the small bridge from using tools to making one. A chore you repeat — trimming a stray space off a term, capitalising a heading the house style's way, tagging each entry with its length — gets wrapped up once, under a name you choose, and from then on asking for it again costs one word. Naming work is the entire trick of reuse: the mistake you might have made by hand the fifth tired time simply never happens, because the fifth time is the same two lines as the first.
Two modules, then, and a promise worth stating: nothing in them is mathematical. The skill being trained is the one you already own — choosing a precise name for a piece of work, and trusting that a named thing means the same thing every time you say it. By the end of the track, "what would I call this chore?" becomes a question you ask about your own working day, and the next track — loops — is what lets your named chore run over an entire list while you watch.