Index Ai Academy
Phase 0 · ToolsPython core

Numbers and arithmetic

About 20 minLooking ahead: some prerequisites aren't done yet

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

OperatorMeaningExampleResult
+add1200 + 3401540
-subtract5000 - 3120.51879.5
*multiply2.5 * 4001000.0
/divide1920 / 240000.08
//divide, rounding down to a whole number2340 // 5004
%remainder after dividing2340 % 500340
**to the power of1.05 ** 31.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, like 500.
  • Floats (float) have a decimal point, like 1250.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:

  1. ** first,
  2. then *, /, // and %,
  3. 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)