Login
📚 Introduction to Python Programming
Chapters ▾

4.4 Operator precedence

Learning objectives

By the end of this section you should be able to

  • Describe how precedence impacts order of operations.
  • Describe how associativity impacts order of operations.
  • Explain the purpose of using parentheses in expressions with multiple operators.

Precedence

When an expression has multiple operators, which operator is evaluated first? Precedence rules provide the priority level of operators. Operators with the highest precedence execute first. Ex: 1 + 2 * 3 is 7 because multiplication takes precedence over addition. However, (1 + 2) * 3 is 9 because parentheses take precedence over multiplication.

Table 4.4 Operator precedence from highest to lowest.
OperatorMeaning
Parentheses
**Exponentiation (right associative)
*, /, //, %Multiplication, division, floor division, modulo
+, -Addition, subtraction
<, <=, >, >=, ==, !=Comparison operators
notLogical not operator
andLogical and operator
orLogical or operator

Associativity

What if operators beside each other have the same level of precedence? Associativity determines the order of operations when precedence is the same. Ex: 8 / 4 * 3 is evaluated as (8/4) * 3 rather than 8 / (4*3) because multiplication and division are left associative. Most operators are left associative and are evaluated from left to right. Exponentiation is the main exception (noted above) and is right associative: that is, evaluated from right to left. Ex: 2 ** 3 ** 4 is evaluated as 2 ** (3**4).

When comparison operators are chained, the expression is converted into the equivalent combination of comparisons and evaluated from left to right. Ex. 10 < x <= 20 is evaluated as 10 < x and x <= 20.

Enforcing order and clarity with parentheses

Operator precedence rules can be hard to remember. Parentheses not only assert a different order of operations but also reduce confusion.