Skip to main content

Section 4.6 Precedence of Operators

We have now added a number of additional operators to those we learned in the previous chapters. It is important to understand how these operators relate to the others with respect to operator precedence.
Python will always evaluate the arithmetic operators first (** is highest, then multiplication/division, then addition/subtraction). Next come the relational operators. Finally, the logical operators are done last. This means that the expression x * 5 >= 10 and y - 6 <= 20 will be evaluated so as to first perform the arithmetic and then check the relationships. The and will be done last. Although many programmers might place parentheses around the two relational expressions, it is not necessary.
That having been said, when in doubt, use parentheses. In fact, even when you aren’t in doubt, use parentheses!!! For example, quick—without looking at the table of priorities—which logical operations happen in which order in this boolean expression?
age < 21 or day == 6 and hour > 15 and not month < 6 or month > 9
Without parentheses, this is totally confusing, even to people who have memorized the precedence table.
If you ever encounter code like the preceding monstrosity, you’ll need the following table to help you untangle the mess. The table summarizes the precedence discussed so far from highest to lowest. See Section 1 for all the operators introduced in this book.
Table 4.6.1.
Level Category Operators
7(high) exponent **
6 multiplicative *,/,//,%
5 additive +,-
4 relational ==,!=,<=,>=,>,<
3 logical not
2 logical and
1(low) logical or

Note 4.6.2.

This workspace is provided for your convenience. You can use this activecode window to try out anything you like.

Checkpoint 4.6.3.

    Which of the following properly expresses the precedence of operators (using parentheses) in the following expression: 5 * 3 > 10 and 4 + 6 == 11
  • ((5 * 3) > 10) and ((4 + 6) == 11)
  • Yes, * and + have higher precedence, followed by > and ==, and then the keyword "and"
  • (5 * (3 > 10)) and (4 + (6 == 11))
  • Arithmetic operators (*, +) have higher precedence than comparison operators (>, ==)
  • ((((5 * 3) > 10) and 4) + 6) == 11
  • This grouping assumes Python simply evaluates from left to right, which is incorrect. It follows the precedence listed in the table in this section.
  • ((5 * 3) > (10 and (4 + 6))) == 11
  • This grouping assumes that and has a higher precedence than ==, which is not the case.
Here is an animation for the preceding expression:

Checkpoint 4.6.4.

5 * 3 > 10 and 4 + 6 == 11