Definition
Operator precedence is the order in which Python evaluates the parts of an expression when several operators appear together. Operators with higher precedence run first, and brackets override everything.
In simple words
It's BODMAS for code. 2 + 3 * 4 is 14, not 20, because multiplication goes first. When in doubt, add brackets, and the next reader will thank you.
Why it matters
A wrong assumption here gives a wrong answer with no error at all, so it's a hard bug to find.
How it works
| Order | Operators |
|---|---|
| 1 | ( ) |
| 2 | ** |
| 3 | +x, −x, ~x |
| 4 | *, /, //, % |
| 5 | +, − |
| 6 | <<, >> |
| 7 | & |
| 8 | ^ |
| 9 | | |
| 10 | ==, !=, >, <, >=, <=, is, in |
| 11 | not |
| 12 | and |
| 13 | or |
In code
print(2 + 3 * 4)
print((2 + 3) * 4)
print(2 ** 3 ** 2)
print(-2 ** 2)
print(10 - 4 - 3)
print(True or False and False)
print(not True or True)Output
14 20 512 -4 3 True True
Common mistakes
- Assuming and and or have equal priority. and runs first.
- Writing long expressions with no brackets to look clever.
Check yourself
Summary
- Python follows a fixed order, much like BODMAS.
- Brackets override it, so use them when unsure.
Finished reading?
Sources: The Python Tutorial, python.org