6. Precedence

When an expression mixes operators, Python evaluates them in a fixed order called precedence. Operators with higher precedence bind first.

From highest to lowest, the operators used in this chapter are:

  1. ** (power)
  2. unary + and - (for example -x)
  3. *, /, //, %
  4. +, -
  5. comparisons (<, <=, >, >=, ==, !=)
  6. not
  7. and
  8. or

Operators on the same level are evaluated from left to right, except **, which groups from right to left.

Parentheses () override precedence: whatever is inside them is evaluated first.

Unary minus has lower precedence than **, so -2 ** 2 means -(2 ** 2):

not has lower precedence than comparisons, so not 2 > 3 means not (2 > 3).

and has higher precedence than or, so True or False and False means True or (False and False).

#01

Multiplication before addition

Write 2 + 3 * 4 without parentheses, and print the result. Multiplication is evaluated before addition.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Parentheses first

Use parentheses to force 2 + 3 to be evaluated before multiplying by 4, and print the result.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Power before multiplication

Write 2 * 3 ** 2 without parentheses, and print the result. The power operator (**) has higher precedence than multiplication.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Unary minus and power

Print -2 ** 2 without parentheses. The power operator (**) is evaluated before the unary minus, so the minus applies to the whole result of 2 ** 2.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#05

not and comparison

Print not 2 > 3 without parentheses. Comparisons are evaluated before not, so not applies to the result of 2 > 3.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#06

and before or

Print True or False and False without parentheses. The and operator is evaluated before or.

Print exactly:

Create a free account to save your progress and unlock chapter 2.