🎓 A1Learner
🔍

Python Operator Precedence

Precedence is the fixed order Python uses to work out the parts of an expression. Brackets change the answer in maths.

Brackets go first

Brackets beat every other sign in the line.

print((2 + 3) * 4)

Power before plus

Python works out the power before it adds.

print(2 + 2 ** 3)

Times before plus

Python works out the times part before it adds.

print(2 + 3 * 4)

Comparisons after maths

Python adds first, then it compares the answer.

print(5 + 3 > 7)

not, then and, then or

The word and is worked out before the word or.

print(not False and True)
print(False or True and False)

Chain two comparisons

This short form asks if x sits between 1 and 10.

x = 5
print(1 < x < 10)

Example

print("First:", 2 + 3 * 4)
print("Second:", (2 + 3) * 4)
print("Third:", 2 ** 3 + 1)
print("Fourth:", 10 - 2 * 3)
print("Fifth:", 5 + 3 > 7 and not False)

Key points

  • Precedence: the order Python uses to work out the parts of an expression.
  • First come brackets, then **, then * / // and %, then + and -.
  • After maths come comparisons, then not, then and, then or.
  • A chained comparison like 1 < x < 10 checks that x sits between 1 and 10.
  • When in doubt, add brackets.
  • They make your meaning clear at a glance.
  • (-2) ** 2 gives 4.

In this example, the first line does times before plus and gets 14. Brackets change the second line and the answer is 20. The third line does the power first and gets 9. The fourth line does times before minus and gets 4. In the fifth line, Python adds first and gets 8, then compares, then flips with not, then joins with and.

Note

** wins over a minus sign on its left.

So -2 ** 2 gives -4.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What is the value of 3 + 4 * 2?