Functions in Python: write the math once, use it for every product
You've worked out the margin on a tee. Now there are pants, socks, and a hoodie. Retyping the formula for each one is how errors creep in. A function captures it once.
The big idea
A function is a named block of code that takes inputs through parameters and hands back a result with return.
See it in code
def names the function and lists its parameters. return sends the answer back to whoever called it:
def margin(price, cost):
return (price - cost) / price
print(f"Tee margin: {margin(38, 14):.1%}")Tee margin: 63.2%
margin(38, 14) evaluated to 0.6316 and was dropped straight into the f-string. The function body ran only because something called it.
The same function answers a different question every time you change its arguments. A second function can lean on a module:
import math
def margin(price, cost):
return (price - cost) / price
def break_even(fixed_costs, price, cost):
return math.ceil(fixed_costs / (price - cost))
print(f"Pants margin: {margin(78, 29):.1%}")
print(f"Hoodie margin: {margin(64, 24):.1%}")
print("Tees to break even:", break_even(12500, 38, 14))Pants margin: 62.8% Hoodie margin: 62.5% Tees to break even: 521
Each call binds its own values to price and cost. Nothing about pants leaks into the hoodie calculation; every call starts fresh.
The real payoff is calling a function in a loop. One definition now covers the whole catalog, and any product added later:
def margin(price, cost):
return (price - cost) / price
names = ["Tee", "Pants", "Socks", "Hoodie"]
prices = [38, 78, 14, 64]
costs = [14, 29, 4, 24]
for i in range(len(names)):
print(f"{names[i]} margin: {margin(prices[i], costs[i]):.1%}")Tee margin: 63.2% Pants margin: 62.8% Socks margin: 71.4% Hoodie margin: 62.5%
The cheapest item, socks, has the best margin. That's the kind of insight you only see once the calculation is cheap enough to run on everything.
The same move tidies every domain: a function to transcribe DNA, to compute a moving average, to hash a block. Name the operation once, then think in terms of it.
Try it yourself
Add a fifth product to all three lists and re-run; no formula needs touching. Then write season_profit(price, cost, units) and print it for 500 tees and 200 pairs of pants.
The common mistake
Calling a function before it's defined. Python runs top to bottom, so a call above its def raises NameError. Definitions go first; the code that uses them goes below.
What it unlocks
Make functions flexible with default and keyword arguments, understand exactly what return does, and learn where a function's variables live in scope.