Skip to main content

Section 6.5 Precedence of Operators

Arithmetic operators take precedence over logical operators. Python will always evaluate the arithmetic operators first (** is highest, then multiplication/division, then addition/subtraction). Next comes 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. Many programmers might place parentheses around the two relational expressions, (x*5 >= 10) and (y-6 <= 20). This is not necessary, but if often makes it easier for people to read and understand the code.
The following table summarizes the operator precedence from highest to lowest. A complete table for the entire language can be found in the Python Documentation
 1 
http://docs.python.org/py3k/reference/expressions.html#expression-lists
.
Table 6.5.1.
Level Category Operators
7(high) exponent **
6 multiplication *,/,//,%
5 addition +,-
4 relational ==,!=,<=,>=,>,<
3 logical not
2 logical and
1(low) logical or

Note 6.5.2.

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

Note 6.5.3. Common Mistake!

Students often incorrectly combine the in and or operators. For example, if they want to check that the letter x is inside of either of two variables then they tend to write it the following way: 'x' in y or z
Written this way, the code would not always do what the programmer intended. This is because the in operator is only on the left side of the or statement. It doesn’t get implemented on both sides of the or statement. In order to properly check that x is inside of either variable, the in operator must be used on both sides which looks like this:
'x' in y or 'x' in z
Check your understanding

Checkpoint 6.5.4.

    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:

Checkpoint 6.5.5.

5 * 3 > 10 and 4 + 6 == 11
You have attempted of activities on this page.