Chapter 5: Operators and Expressions

Operator precedence

face Josiah Wang

You can also chain expressions, e.g. 7 + 2 * 3.

Python largely obeys a standard order of operations in Mathematics.

More specifically, the operator precedence in Python is as follows.

  1. ( )
  2. **
  3. * // / %
  4. + -

If at equal precedence (e.g. multiplication and division), the expression is evaluated from left to right like in Mathematics.

Check whether you understand this with the quiz below!

1 2 3

Question 1

What is the value of the following expression?

7 + 2 * 3

13
Explanation:

Evaluated as 7 + (2 \times 3). Python recommends you write this as 7 + 2*3 for better clarity.

Question 2

What is the value of the following expression?

7 * 3 / 2

10.5
Explanation:

Since multiplication and division has the same operator precedence, this expression is evaluated from left to right: \frac{(7 \times 3)}{2}. Python recommends you write this as 7*3 / 2 for better clarity.

Question 3

What is the value of the following expression?

(7 + 2) / 3 ** 2 - 5 

-4.0
Explanation:

Parenthesis is executed first (7 + 2) resulting in 9. This is followed by exponentiation 3 ** 2 also resulting in 9. Then division 9 / 9 resulting in 1.0 (remember that division always results in a float). Finally the subtraction 1.0 - 5 results in -4.0. In Mathematical notation, this is \\\frac{(7 + 2)}{3^2}-5. This expression could perhaps be rewritten as ((7+2) / 3**2) - 5 which makes it clearer.