Operator Precedence and Associativity of Operators

Precedence and Associativity of Operators

                    If more than one operator appears in an expression, then the order of evaluation depends on the rules of precedence. For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the rules:

simplepycoder.operator_precedence

                    Every operator in Python has precedence associated with it. The precedence is used to determine how an expression involving more than one operator is evaluated. The operator which has higher precedence are evaluated first. The operators of the same precedence evaluated either from left to right or right to left depending on the level is known as associativity.

The hierarchy of operators in Python are summarised below:

  • Any expression within parenthesis is first evaluated, if more than one pair of parenthesis are present, the innermost parenthesis is evaluated first.
  • First unary operators are evaluated in an expression.
  • The next priority is given to multiplication and division operators.
  • Next, the subtraction and addition operations are performed.
  • Then relational operators are performed.
  • Then equality checking operation is performed.
  • Next logical operations are performed.
  • Next, the conditions are checked.
  • Finally, the assignment operator will work.

The following table lists all operators from highest to lowest precedence:

Operators

Description

**

Exponentiation  (raise  to  the  power)

~   + -

Complement, unary plus and minus.

*  /  %  //

Multiply, divide, modulo and floor division.

+  -

Addition, Subtraction.

>>   <<

Right and Left bitwise shift.

&

Bitwise   ‘AND’

^   |

Bitwise exclusive ‘OR’ and regular ‘OR’.

<=   <

>   >=

Comparison Operators.

<  >   = =   ! =

Equality  Operators.

=  % =

/ =  // =

- =  + =

* =    **=

Assignment operators.

is, is not

Identity operators.

in,  not in

Membership operators.

not  or  and

Logical operators.

          

0/Post a Comment/Comments

Previous Post Next Post