When an expression has several operators, Python does not simply evaluate them from left to right: it follows an order of priority, just like in maths. Knowing it avoids many unexpected results.
Order of priority (highest to lowest)
| Priority | Operators | Example |
|---|---|---|
| 1st (highest) | Parentheses ( ) | (2 + 3) * 4 |
| 2nd | Power ** | 2 ** 3 |
| 3rd | Unary sign -x, +x | -5 |
| 4th | * / // % | 6 * 2 / 3 |
| 5th (lowest) | + - | 1 + 2 - 3 |
Examples
print(2 + 3 * 4) # 14 (3 * 4 first)
print((2 + 3) * 4) # 20 (the parentheses go first)
Operators of the same level are evaluated from left to right:
print(10 - 4 - 3) # 3 ((10 - 4) - 3)
print(100 / 10 * 2) # 20.0
print(100 / (10 * 2)) # 5.0
Power is special
** is evaluated from right to left, and it has higher priority than the minus sign in front of it:
print(2 ** 3 ** 2) # 512 (2 ** 9)
print(-2 ** 2) # -4 (the minus is applied afterwards)
print((-2) ** 2) # 4
Distributive property
The rules are those of maths, so (a + b) * c and a * c + b * c always give the same result. Without parentheses, a + b * c is something different.
Tips
- When in doubt, add parentheses: they cost nothing and make the expression clearer.
- If a formula is long, split it into steps with intermediate variables.
- Be careful with divisions:
a / b * cis not the same asa / (b * c).
Practice in the exercises about order of priority, equivalent operations and calculating the values of a function.