Skip to content

Understanding operator precedence

Understanding operator precedence

When you create simple statements that contain just one operator, the order of determining the output of that operator is also simple. However, when you start working with multiple operators, it becomes necessary to determine which operator to evaluate first. For example, it’s important to know whether 1 + 2 * 3 evaluates to 7 (where the multiplication is done first) or 9 (where  the addition is done first). An order of operator precedence tells you that the answer is 7 unless you use parentheses to override the default order. In this case, (1 + 2) * 3 would evaluate to 9 because the parentheses have a higher order of precedence than multiplication does. Table 6-9 defines the order of operator precedence for Python.

 

 

Table 6-9                        Python Operator Precedence

 

Operator                                                  Description

()                      You use parentheses to group expressions and to override the default precedence so that you can force an operation of lower precedence (such as addition) to take pre­ cedence over an operation of higher prece­ dence (such as multiplication).

 

**                      Exponentiation raises the value of the left operand to the power of the right operand.

 

~ + –                   Unary operators interact with a single vari­ able or expression.

 

  • / % // Multiply, divide, modulo, and floor

+ –                     Addition and subtraction.

>> <<                   Right and left bitwise shift.

&                       Bitwise AND.

^ |                     Bitwise exclusive OR and standard OR.

<= < > >=                Comparison operators.

== !=                   Equality operators.

 

= %= /= //= -= += *=

**=

Is

is not In

not in

Assignment operators. Identity operators.

 

Membership operators.

 

not or and               Logical operators.