the full guide

Operator precedence

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.

4 min Intermediate

What you need: The earlier topics of this module.

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

OrderOperators
1( )
2**
3+x, −x, ~x
4*, /, //, %
5+, −
6<<, >>
7&
8^
9|
10==, !=, >, <, >=, <=, is, in
11not
12and
13or

In code

precedence.py
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

Question 1

1. What is 2 + 3 ** 2?

Question 2

2. What is True or False and False?

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