Numbers and arithmetic
Why this matters
Machine learning is arithmetic at enormous scale. A model's prediction is a long chain of multiplications and additions. Its training "loss" is a single number. The probability, token count and dollar cost of every API call are numbers too. You already work with rates and ratios at work. This lesson shows how to make Python do it, and where its arithmetic can surprise you.
- Calculate with +, -, *, /, //, % and ** and predict the result
- Control the order of a calculation with parentheses
- Round results, and explain why 0.1 + 0.2 isn't exactly 0.3
- Convert between text and numbers with int(), float() and str()
The arithmetic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | add | 1200 + 340 | 1540 |
- | subtract | 5000 - 3120.5 | 1879.5 |
* | multiply | 2.5 * 400 | 1000.0 |
/ | divide | 1920 / 24000 | 0.08 |
// | divide, rounding down to a whole number | 2340 // 500 | 4 |
% | remainder after dividing | 2340 % 500 | 340 |
** | to the power of | 1.05 ** 3 | 1.157625 |
spend = 1250.50 clicks = 500 print("Cost per click:", spend / clicks) print("Spend doubled:", spend * 2)
Python has two kinds of number:
- Integers (
int) are whole numbers, like500. - Floats (
float) have a decimal point, like1250.5.
Mix them in a calculation, and the result is a float. Division with / always gives a float, even when it divides evenly:
print(10 / 2) print(type(10 / 2))
Long numbers are easier to read with underscores, which Python ignores: impressions = 1_250_000.
Order of operations
Python follows the order you learned in school:
**first,- then
*,/,//and%, - then
+and-.
Operators at the same level go left to right. Parentheses override all of it. Use them whenever the order matters, even if you think Python would get it right anyway. They make your meaning obvious to the next reader.
revenue = 15840 cost = 3120.5 wrong_margin = revenue - cost / revenue # divides first, then subtracts margin = (revenue - cost) / revenue # what we actually meant print(wrong_margin) print(margin)