From Notebook Cells to Functions
A notebook that answers this week's questions has to be edited by hand for next week's file, so the cells you run again and again become functions whose parameters are what changes, such as the file and how many top items to show, and which return their results instead of printing them.
Journeyman · Python · Updated
After this lesson you can
- Turn cells you rerun for each new file into a function with parameters for what changes, such as the file to load and how many top items to show
- Return a function's results instead of printing them, so a notebook, a report or a test can use them
Key takeaways
- A cell you rerun with a new file name or a new number is a function waiting to be written. What changes each time becomes a parameter.
- load_week(path) loads any week, so two weeks can sit side by side without copying a single cell.
- print shows a value on the screen and hands back nothing (None). return hands the value back, so other code can compare it, chart it or test it.
- A number buried in a cell, such as the 3 in head(3), belongs in a parameter with a default, such as n=3.
An analysis that answers a question once is a good start. The trouble starts when the same question comes back every week: the club's attendance every month, a lab's readings every Monday, a store's sales every week. If the answer lives in notebook cells you edit by hand, every week is a fresh chance to change one cell and forget another. Turning those cells into functions is the first step toward a report that rebuilds itself.
The example all chapter is the Greenway Food Truck. Each week a file of its sales arrives in data/incoming/, named by the Monday the week starts on: week-2026-09-07.csv, week-2026-09-14.csv and on, eight weeks so far, about 400 sales each. Each row is one sale: sold_at (the date and time), location (City Park, Office Row or Stadium, wherever the truck parked that day), item, quantity, price (for one item) and payment. Dana, who owns the truck, wants the same numbers every Monday.
The notebook that worked once
Here's the first week, answered in three cells. (VS Code draws the tables as a grid; here they're shown as text.)
import pandas as pd
week = pd.read_csv("data/incoming/week-2026-09-07.csv")
week[["sold_at", "location", "item", "quantity", "price"]].head(3)
sold_at location item quantity price
0 2026-09-07 11:01 Office Row Quesadilla 1 8.5
1 2026-09-07 11:04 Office Row Loaded Fries 1 6.5
2 2026-09-07 11:06 Office Row Street Tacos 1 9.0
week["total"] = week["quantity"] * week["price"]
print("sales:", week["total"].sum())
print("items sold:", week["quantity"].sum())
sales: 4653.5
items sold: 564
week.groupby("item")["quantity"].sum().sort_values(ascending=False).head(3)
item
Street Tacos 157
Burrito Bowl 127
Quesadilla 102
Name: quantity, dtype: int64
It works. Now it's the next Monday. You change the file name in the first cell, run every cell again, and copy the numbers into a message to Dana. Then she asks how this week compares with last week, and the notebook can't say: week holds one week at a time. Copying all three cells and renaming week to week2 in each is how mistakes creep in. And the 3 in head(3) is a hard-coded value: a number typed into the code where nobody will think to look for it when Dana asks for the top five.
A function for each job
The fix is to notice what changes each week (the file) and what stays the same (everything else). What stays the same becomes the body of a function; what changes becomes its parameter, the name in the parentheses that gets a new value each time the function is called:
def load_week(path):
week = pd.read_csv(path)
week["total"] = week["quantity"] * week["price"]
return week
first = load_week("data/incoming/week-2026-09-07.csv")
second = load_week("data/incoming/week-2026-09-14.csv")
print("first week:", len(first), "sales")
print("second week:", len(second), "sales")
first week: 409 sales
second week: 422 sales
Two weeks, side by side, and the loading code was written once. A mistake fixed in load_week is fixed for every week.
Return the answer, don't print it
A cell that ends with print is made for your eyes. Turned into a function, it shows the number and hands nothing back:
def show_sales(week):
print("sales:", week["total"].sum())
result = show_sales(first)
print("result:", result)
sales: 4653.5
result: None
None is Python's word for "nothing here". The number reached the screen, but result got nothing, so no other code can use it. return hands the value back to the line that called the function. That value is the function's return value, and it can be stored, compared or tested:
def total_sales(week):
return week["total"].sum()
change = total_sales(second) - total_sales(first)
print("change:", change)
change: 110.5
Sales were $110.50 higher in the second week. A function that returns its answer can feed a comparison, a chart, a web page or a test; one that prints can only feed your eyes.
Numbers that belong in parameters
The 3 from the third cell becomes a parameter too. Giving it a default value, n=3, keeps the usual case short and lets Dana's top five be n=5:
def top_items(week, n=3):
counts = week.groupby("item")["quantity"].sum()
return counts.sort_values(ascending=False).head(n)
top_items(second, n=2)
item
Burrito Bowl 141
Street Tacos 139
Name: quantity, dtype: int64
The headline numbers can come back together as a dictionary, one name for each number. float() and int() turn pandas' numbers into plain Python ones, so the dictionary prints cleanly:
def summarize(week):
return {
"sales": float(week["total"].sum()),
"items_sold": int(week["quantity"].sum()),
"best_item": top_items(week, n=1).index[0],
}
summarize(second)
{'sales': 4764.0, 'items_sold': 583, 'best_item': 'Burrito Bowl'}
The Burrito Bowl outsold the Street Tacos in the second week, and nothing had to be copied to find out. Any week is now two lines: load_week with its file, then summarize. The next step is moving these functions out of the notebook into a .py file of their own, which Your Own Modules and Packages shows and Using Your Module in a Notebook: autoreload puts to work.
Check yourself
2 questions to try on the lesson page.
So what
When the same question comes back every week, the code that answers it should be written once: functions whose parameters are what changes, and which return their answers so other code can use them.