Skip to content
Tactiverge

Python reference

Operator precedence

Also called: order of operations · BIDMAS · PEMDAS · brackets

Definition

Python evaluates ** first, then unary minus, then *, /, // and %, then + and −, then comparisons, then not, and, or. Brackets override everything.

Picture it

When in doubt, add brackets: they cost nothing and show your intent. Two traps: ** binds tighter than unary minus, so -2 ** 2 is -4; and ** groups from the right, so 2 ** 3 ** 2 is 2 ** 9.

Worked example

Evaluate 2 + 3 * 4 ** 2, -2 ** 2 and 2 ** 3 ** 2.

  1. 4 ** 2 = 16, 3 * 16 = 48, 2 + 48 = 50
  2. -(2 ** 2) = -4
  3. 3 ** 2 = 9 first, then 2 ** 9 = 512

Answer50, -4 and 512.

✓ The 3 numbers in this answer are recomputed from scratch by an automated test.

In Python

v_in, r1, r2 = 5, 10_000, 20_000
wrong = v_in * r2 / r1 + r2      # 20010.0
right = v_in * r2 / (r1 + r2)    # 3.33...

Common misconceptions

  • Misconception: Multiplication does not always happen before division; they share a level and go left to right.
  • Misconception: not a == b means not (a == b), which is usually what you want, but surprises people reading it.