Variables in Python: name your numbers, then let them work
A tee costs $14 to make and sells for $38. What does the company keep? Put those two numbers in variables and Python answers that, and every question built on it.
The big idea
A variable is a name bound to a value; use the name anywhere and Python substitutes the value it currently holds.
See it in code
Assignment reads right to left: evaluate the right side, then bind the name on the left to the result. After that, the name can be used in any expression:
price = 38
cost = 14
profit = price - cost
print("Profit per tee:", profit)Profit per tee: 24
profit wasn't typed in as 24. It was computed from the other two, so it can never drift out of step with them.
A variable can be updated using its own current value. Python evaluates the right side first, with the old value, then rebinds the name:
tees_sold = 500
extra_tees = 150
print("Sold so far:", tees_sold)
tees_sold = tees_sold + extra_tees
print("After the restock:", tees_sold)Sold so far: 500 After the restock: 650
tees_sold = tees_sold + extra_tees isn't an equation. It's an instruction: read the old value, add to it, store the result back under the same name.
Now chain them. Every figure below is derived from three starting values, which is exactly how a founder's model should work:
price = 38
cost = 14
tees_sold = 650
profit = price - cost
margin = profit / price
revenue = price * tees_sold
season_profit = profit * tees_sold
print("Profit per tee:", profit)
print("Margin:", margin)
print("Revenue:", revenue)
print("Season profit:", season_profit)Profit per tee: 24 Margin: 0.631578947368421 Revenue: 24700 Season profit: 15600
Change price to 42 and four results update together. That's the payoff of naming values: the model answers "what if?" without you redoing any arithmetic.
The same habit runs through every field that models something. A biologist names a sequence length, a trader names a window size, and a web page names the element it is about to change.
Try it yourself
Set price = 42 and run it again. Then add cost_of_goods = cost * tees_sold and print revenue - cost_of_goods. It should match season_profit exactly, which is a good way to check your own model.
The common mistake
Using a name before it exists. Python runs top to bottom, so margin = profit / price above the line that creates profit raises NameError: name 'profit' is not defined. Define first, then use.
What it unlocks
Variables hold values of different types, and operators combine them. Once a loop is updating one on every pass, you have an accumulator.