Learning LibraryCore Coding LibraryTeens

Operators in Python: arithmetic that decides real answers

Margins, shipping boxes, growth rates: a business is arithmetic all the way down. Python has an operator for each job, and two of them are easy to confuse.

The big idea

Python's arithmetic operators are +, -, *, / (true division), // (whole-number division), % (remainder), and ** (power).

See it in code

1The basics

/ is true division. It always produces a float, which is what you want for a ratio like margin:

python
price = 38
cost = 14
profit = price - cost
print(profit / price)
Run it. What share of the price is profit?
0.631578947368421

About 0.63, or a 63% margin. Don't worry about the long decimal yet; formatting it is a job for an f-string.

2A step further

For counting whole things, use // and % together. One gives how many full groups fit; the other gives what's left over:

python
tees = 1000
box_size = 24
print("Full boxes:", tees // box_size)
print("Left over:", tees % box_size)
Run it. Packing 1,000 tees into boxes of 24:
Full boxes: 41
Left over: 16

41 full boxes, with 16 tees left for a partial one. Check it: 41 × 24 + 16 is exactly 1,000.

3At Evergreen

Operators have precedence: * and / run before + and -. Here is the profit on a two-tee order, written carelessly and then correctly:

python
price = 38
cost = 14
tees_in_order = 2

print(price - cost * tees_in_order)
print((price - cost) * tees_in_order)
Run it. Same numbers, different grouping:
10
48

The first line computed cost * tees_in_order first, then subtracted: 38 − 28 = 10. Parentheses force the subtraction to happen first, giving the true profit of 48.

The same idea, everywhere

The same operators carry every quantitative course. % wraps an index around a list, // buckets values into a histogram, and ** compounds a growth rate month after month.

Try it yourself

Compute 300 * 1.15 ** 12 to see where 300 tees a month ends up after a year of 15% growth. Then predict what 300 * 1.15 * 12 gives instead, and why that one is wrong.

The common mistake

Trusting left-to-right reading. price - cost * tees_in_order looks like "profit times quantity" but isn't. When an expression mixes +/- with *//, add parentheses to say what you mean.

What it unlocks

Results of arithmetic get tested with comparison operators. For rounding up, square roots, and logarithms, bring in the math module.

Want the simpler version? Read the Kids version →