What is 4 + 3 × 2? If one person gets 14 and another gets 10, a calculation means two things, and nobody can trust it. So everyone agrees on an order. Python follows the same order, and every formula in AI depends on it. This lesson shows the order, how brackets override it, and how to give numbers names so a long calculation reads like plain sense.
What you'll be able to do
Work a calculation in the agreed order: brackets, powers, multiply and divide, then add and subtract
Place brackets to make a calculation mean what you intend
Give numbers names in Python with variables, and print a label with a value
Read a model's formula, such as w * x + b, in the right order
Quick check
Have a guess before you start. What is 4 + 3 × 2 − 1?
9
11
13
7
Show the answer
9
Multiplying comes before adding: 3 × 2 = 6 first. Then left to right: 4 + 6 = 10, and 10 − 1 = 9. Working strictly left to right gives 13, which is the slip this lesson is about.
The math: one calculation, one answer
Purpose. A calculation has to mean the same thing to everyone who reads it, so there's an agreed order:
Brackets first: anything inside brackets is worked out before the rest.
Powers, like 3² (you'll meet them properly in the powers lesson).
Multiply and divide, from left to right.
Add and subtract, from left to right.
So in 4 + 3 × 2 − 1, the multiplication goes first: 3 × 2 = 6. That leaves 4 + 6 − 1, which you work left to right: 10, then 9.
Brackets override the order. If you meant "4 plus 3, then times 2", write it: (4 + 3) × 2 = 14. Brackets say "do this part first", whatever it holds.
The flow below works 4 + 3 × 2 − 1 one operation at a time, and its picture draws the calculation as a tree. Each operation sits above the two numbers it works on, so the one that happens last is at the top. Each step folds one operation into its answer, from the bottom up, until a single number is left.
Try it now
Each step does the one operation that the order says comes next, and the tree folds it into its answer. Set the expression to (4 + 3) * (2 - 1) and press Use these numbers: the brackets put + and − under the ×, so they go first.
Symbols and formula. The order isn't a formula, but it has a short name you can remember: Brackets, then Powers, then Multiply and Divide, then Add and Subtract.
In plain words: do the inside of brackets first, then the "stronger" operations (powers, then times and divide), then the "weaker" ones (plus and minus). Among equals, go left to right.
Left to right matters for equals. 20 − 5 + 3 is 18, not 12: first 20 − 5 = 15, then 15 + 3 = 18. The same for division: 12 ÷ 2 × 3 is 18, because 12 ÷ 2 = 6 comes first.
A fraction bar is a bracket. In 46+2, the whole top is worked out first: 8 ÷ 4 = 2. When you type that on one line, you have to type the brackets yourself: (6 + 2) / 4.
Quick check
What is 20 − 5 + 3?
28
12
22
18
Show the answer
18
Adding and subtracting are equals, so go left to right: 20 − 5 = 15, then 15 + 3 = 18.
Brackets inside brackets. Brackets can nest, like boxes inside boxes. Work from the innermost pair outward: in 2 × ((3 + 1) × 5), the inner (3 + 1) = 4 comes first, then 4 × 5 = 20, then 2 × 20 = 40.
Why have an order at all? Without one, "4 + 3 × 2" is a riddle with two answers. With it, there's exactly one, and anyone reading the line, or any calculator or computer, gets the same result. Multiplying binds more tightly than adding because a product like 3 × 2 is really one quantity: three groups of two. You count that quantity before adding it to anything.
Quick check
Where do brackets go so that 2 + 3 × 4 equals 20?
(2 + 3) × 4
No brackets can do it
(2) + 3 × 4
2 + (3 × 4)
Show the answer
(2 + 3) × 4
(2 + 3) × 4 = 5 × 4 = 20. The brackets make the addition go first.
In your own words
In your own words: what do brackets do to the order of a calculation?
Write a sentence or two, then compare it with a good answer in the lesson.
In Python: the same order, and names for numbers
Purpose. Python follows exactly the same order, so it agrees with you whenever you're right, and catches you when you slip. Spaces are just for people: 4+3*2 and 4 + 3 * 2 mean the same.
It runs right here in your browser, with nothing to install.
Long calculations are easier to read when their parts have names. A variable is a name for a number. You make one with =, which means "store this value under this name":
Read total = price * count as "work out price times count, and store it as total". The right side is worked out first, then the answer is stored under the name on the left.
Printing a label with a value. An f-string is text with an f in front of the quotes. Inside it, a name in curly brackets is swapped for its value:
That prints 3 bars at 12 each: 36. You can put a whole calculation inside the curly brackets.
A named mistake: = doesn't mean "equals forever". It stores a value once. If a later line changes price, the total you stored earlier doesn't update by itself:
price = 12
total = price * 3
price = 15print(total) # still 36: total was worked out when price was 12
Good names. A name can be any word made of letters, digits and underscores, as long as it doesn't start with a digit. Choose names that say what the number is: price and count beat p and c because the line reads like a sentence. Python cares about capitals, so Price and price are two different names. And a name must be given a value before it's used: printing a name you haven't set stops with a NameError.
Worked example
Worked example: a long sum with named parts
Work out a trail trip's cost, first as one long line, then with named parts, and check they agree.
print(4 * 12 + 2 * 35 + 20)
bars = 4 * 12# 4 trail bars at 12 each
maps = 2 * 35# 2 maps at 35 each
permit = 20
total = bars + maps + permit
print(f"bars {bars}, maps {maps}, permit {permit}: total {total}")
In the lesson you can change this and run it.
The first line is correct but hard to read: you have to know the order to see that the two multiplications happen first. The named version says the same thing in steps, so a reader can check each part: bars are 48, maps are 70, and with the permit the total is 138. Both lines give 138, which is the point: names don't change the arithmetic, they make it easy to check.
Now step through the named version one line at a time. Watch each name appear with its value as its line runs. Then, near the end, bars is given a new value: keep an eye on total when that happens.
Quick check
What does this print?
a = 10
b = a + 5
a = 1print(b, a * 2 + b)
15 17
15 35
15 17.0
6 8
Show the answer
15 17
b was worked out as 10 + 5 = 15 when a was 10, and changing a later doesn't touch it. Then a * 2 + b = 1 × 2 + 15 = 17.
Quick check
Which line computes the average of 8 and 12 correctly?
average = ___
(8 + 12) / 2
8 / 2 + 12
(8 + 12) * 2
8 + 12 / 2
Show the answer
(8 + 12) / 2
The brackets make the adding happen first: 20 / 2 = 10. Without them, only the 12 is halved.
Drill
Name the parts
A trip has 3 nights of camping at 18 each, 2 park passes at 25 each, and a 15 fuel cost. Set camping, passes and total, then print the line total: 119.
In the lesson, your code is checked as you write it.
In your own words
Why might you store parts of a calculation under names instead of writing one long line?
Write a sentence or two, then compare it with a good answer in the lesson.
In AI and ML: reading a model's formula
Purpose. AI formulas are short, and every symbol counts. Read them in the wrong order and you'll compute the wrong thing, with no error message to warn you.
The map below is the same in every lesson of this course: a model learning. Its forward row turns data into a prediction and a score for how wrong it is; its backward row turns that score into better weights. The part this lesson's math lives in is lit.
The simplest model there is predicts a number from one input. For the trail club's tent rentals, it guesses how many tents will be rented from the day's temperature:
y^=w×x+b
In plain words: the prediction ŷ ("y-hat") is the input x times a weight w, plus a starting amount b, the bias.
The multiplication comes first, then the add. In Python that's w * x + b, which Python works in the same order. To see how wrong a prediction is, you subtract the true value and square the gap:
w = 2
b = 3
x = 20# degrees on the day
target = 41# tents actually rented
prediction = w * x + b
print(f"prediction {prediction}, error {prediction - target}, squared {(prediction - target) * (prediction - target)}")
The brackets around (prediction - target) are essential: without them, Python would multiply first and get something else entirely.
In the real tools. In PyTorch, the library most models are built with, the same line works on a whole tensor, many numbers held together, so one line makes a prediction for every day at once:
Quick check
What does this print?
w = 3
x = 10
b = 4print(w * x + b, w * (x + b))
17 42
34 42
42 34
34 34
Show the answer
34 42
w * x + b multiplies first: 30 + 4 = 34. The brackets in w * (x + b) add first: 3 × 14 = 42.
Quick check
A model's error is written prediction − target, all squared. Someone types prediction - target * prediction - target. What happens?
It gives the right answer
Python spots the slip and stops
It runs and gives a wrong number
It squares only the target
Show the answer
It runs and gives a wrong number
Python multiplies target × prediction first, then subtracts. It runs without complaint and gives a wrong number. Brackets make the gap first: (prediction - target) * (prediction - target).
Drill
One prediction and its squared error
With w = 1.5, b = 2, x = 18 and target = 30, set prediction to w times x plus b, error to prediction minus target, and squared to the error times itself.
w = 1.5
b = 2
x = 18
target = 30
prediction = w * (x + b)
error = target - prediction
squared = error * 2print(prediction, error, squared)
In the lesson, your code is checked as you write it.
In your own words
Why are brackets so important in (prediction − target) squared?
Write a sentence or two, then compare it with a good answer in the lesson.
Goes deeper in
Variables: names for values, in the Python lessons.
31Formulas with fractions: clear them firstFreeClearing denominators, cross-multiplying, a letter in the bottom, and reciprocal formulas like 1/R = 1/R₁ + 1/R₂.35 min
37Inverse functions, lines and scalingFreeUndoing a function by making x the subject, domains that allow it, line forms, and unscaling predictions.40 min
38Sequences and sums: find n, a, d and rFreeEvery letter of the arithmetic and geometric formulas as the subject, and an average's window from its decay.40 min
40Review: rearrange anything (algebra)FreeBroken rearrangements to fix, mixed practice from the whole algebra block, a strategy chart, and its formula sheet.35 min
41Coordinates and distanceFreePoints as (x, y), Pythagoras, distance in any number of coordinates, and nearest neighbors.42 min
42Angles, degrees and radiansFreeMeasuring a turn, converting units, arcs, and the angle between two arrows.36 min
43Sine and cosineFreeAcross and up: right triangles, the unit circle, and directions and rotations.42 min
44Waves: height, speed and shiftFreeAmplitude, period and phase, sampling a wave, and position codes in transformers.37 min
68Vector equations: rearranging with arrowsFreeSolving for a vector or a scale, recovering a gradient from two weight snapshots, and an angle from a dot product.40 min
87Counting: choices, orders and groupsFreeThe counting principle, factorials, ordered picks and groups, and why attention's cost grows with the square of the length.43 min
88Probability: from counts to chancesFreeEqually likely outcomes, the complement, distributions, seeded simulation, and a next-word model.43 min
89Combining events: and, or, independentFreeThe or rule, independence, probability trees, drawing with and without replacement, and chains of steps.42 min
100Maximum likelihoodFreeLikelihoods as products, log-likelihoods as sums, grid search, underflow, and the negative log-likelihood loss.45 min
101Linear regression: the best lineFreeResiduals, least squares by formula, three roads to one line, the matrix form, and train versus test error.45 min
109One neuron, start to finishFreeWeighted sum, activation, loss, slopes and update, by hand and in code, and what one straight line can and can't split.45 min
111Training a small networkFreeThe backward pass in matrix form, gradient checks, a full training loop, and reading loss curves.45 min
112The same network in PyTorchFreenn.Sequential with the NumPy weights loaded, the same loss and slopes, then SGD and mini-batches.45 min
113Attention as matrix mathFreeScaled dot-product scores, the causal mask, a row-by-row softmax, and blending value vectors.45 min
114Residual connections and layer normFreeAdding the input back and why its slope keeps learning alive, layer norm by hand, and add and norm.40 min
115A transformer block, start to finishFreeA sentence through embeddings, attention, add and norm, a small network and next-word scores, every shape named.45 min
117Final test: transpose any formulaFreeSlips to fix from every topic, mixed practice of every kind of rearranging, the strategy chart and the full sheet.45 min
Learn the math behind AI from arithmetic up: numbers, algebra, vectors and matrices, calculus, probability and statistics, each shown as numbers moving and checked in Python, ending with a network you build and train from the formulas.
See the course →
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write