Menu

Arithmetic Operations

Order of operations

Python evaluates arithmetic in a fixed order called precedence. It does not simply work from left to right, so knowing the order lets you predict a result and add brackets when you need a different one.

PriorityOperatorsHow to work
1Brackets ( )Innermost brackets first
2Exponentiation **Before the operators below
3Multiplication *, real division /, integer division //, modulo %Left to right
4Addition +, subtraction -Left to right

Multiplication, real division, integer division and modulo share the same priority, so work through them from left to right. For example, 48 // 5 * 2 is 9 * 2 = 18. Addition and subtraction also share a priority: 30 - 7 + 2 is 23 + 2 = 25.

Brackets override the normal order and make your intended order clear. Compare 9 + 4 * 5 ** 2 with (9 + 4) * 5 ** 2. The first gives 9 + 100 = 109, because exponentiation and multiplication happen before addition. The second gives 13 * 25 = 325.

To evaluate an expression for given values, replace each variable with its value and work one step at a time. If a = 20, b = 3 and c = 4, then a - b * c becomes 20 - 3 * 4, then 20 - 12 = 8. With brackets, (a - b) * c becomes (20 - 3) * 4 = 17 * 4 = 68.

Missing brackets can change the result, particularly when a total is shared out. Three friends split the cost of a takeaway: £14 for pizzas, £19 for burgers and £9 for drinks. The correct amount each is (14 + 19 + 9) / 3 = 42 / 3 = 14.0. Without brackets, 14 + 19 + 9 / 3 divides only the £9 by 3, giving 36.0, which is not a share of the bill at all. The brackets make sure all three amounts are added before dividing.

Practise this