Menu

Arithmetic Operators

Order of Precedence

When an expression contains more than one arithmetic operator, the computer does not simply work from left to right. It follows order of precedence: rules that decide which calculation is done first. Change the order and you change the value produced, so every expression in an algorithm must be worked through in the right sequence.

Brackets, indices, then the rest

The usual order is remembered as BIDMAS: brackets, indices (powers), then division and multiplication, then addition and subtraction. Anything in brackets is calculated first, so brackets are how you override the normal order when you want a different result.

Exponentiation, written with **, is finished before any division or multiplication. In 2 + 5 * 3 ** 2 the power is done first (3 ** 2 is 9), then 5 * 9 is 45, and finally 2 is added to give 47. Writing (2 + 5) * 3 ** 2 gives 63 instead, because the bracketed addition is now first. Integer division // and modulus % sit on the same level as * and /.

Equal precedence runs left to right

Multiplication and division carry equal weight, so when they appear together you work from left to right: 36 / 4 * 3 is 9 * 3 = 27, not 36 / 12 = 3. Addition and subtraction also share a level and run left to right: 50 - 15 - 10 is 35 - 10 = 25, not 50 - 5 = 45. Even so, both addition and subtraction are always done after division and multiplication unless brackets say otherwise.

Reading an algorithm line by line, replace each symbol with its correct meaning and apply these rules before storing the result in a variable.

shirt = 12
shorts = 8
discount = 5
order = (shirt + shorts) * 2 - discount
print(order)

Output:

35

Here the brackets are calculated first, so the two prices are added before being doubled, and the discount is only taken away at the end. Without the brackets, shorts * 2 would be worked out before the addition and the total would be different.

Practise this