Hone

Lessons · Python · which operator goes first

Which operator goes first

Multiplication and division happen before addition and subtraction, so 3 + 4 * 2 is 11. Parentheses make the order explicit.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

A price with tax, an average, a discount off a subtotal: one wrong order and every figure on the invoice is wrong while looking plausible.

How to think about it

When an expression mixes operators, put parentheses around the part you mean to happen first, even where Python would have agreed. Code is read more often than it is written.

Worked example

print(3 + 4 * 2)
11: the multiplication happens first.
print((3 + 4) * 2)
14: parentheses first.
print(10 - 4 - 3)
3: equal operators go left to right, so (10 - 4) - 3.
print(2 ** 3 ** 2)
512: ** is the exception, it groups right to left, 2 ** 9.

Your turn

Average of a and b.

avg =  / 2

The trap

a + b / 2 is not the average. Division wins, so half of b is added to a. The parentheses are the whole fix.

Practise which operator goes first on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.