7.3. 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 comes the relational operators, equals, less than, greater than, etc. 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 parenthesis around the two relational expressions, it is not necessary.

The following table summarizes the precedence discussed so far from highest to lowest. See Operator precedence table for all the operators introduced in this book.

Level

Category

Operators

7(high)

exponent

**

6

multiplication

*,/,//,%

5

addition

+,-

4

relational

==,!=,<=,>=,>,<

3

logical

not

2

logical

and

1(low)

logical

or

Check your understanding

    select-3-1: 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 true.

Here is an animation for the above expression:

5 * 3 > 10 and 4 + 6 == 11
You have attempted of activities on this page
7.2. Logical operators"> 7.4. Conditional Execution: Binary Selection">Next Section - 7.4. Conditional Execution: Binary Selection