When an expression has more than one operator, then it is the relative priorities of the operators with respect to each other that determine the order in which the expression is evaluated.

Actually, there are distinct levels of precedence, and an operator may belong to one of the levels. The operators at a higher level of precedence are evaluated first. The operators of the same precedence are evaluated either from left to right or right to left, depending on the level. This is known as the associativity of an operator.

Python supports the following Operator Precedence (highest to lowest) and associativity Chart.

Operator | Description | Associativity |

() | Parentheses | Left to right |

** | Exponentiation | Right to left |

~, +,- | Complement, unary plus (positive), and minus (negative) | Right to left |

*, /, %, // | Multiply, divide, modulo, and floor division | Left to right |

+, - | Addition and subtraction | Left to right |

>>, << | Right and Left bitwise shift | Left to right |

& | Bitwise ‘AND’ | Left to right |

^, | | Bitwise exclusive ‘OR’ and regular ‘OR’ | Left to right |

<=, <, >, >= | Comparison operators | Left to right |

<>, ==, != | Equality operators | Left to right |

=, %=, /=, //=, -=, +=, *=, **= | Assignment operators | Right to left |

Is, is not | Identity operators | Left to right |

In, not in | Membership operators | Left to right |

Not, or, and | Logical operators | Right to left, left to right, left to right |

For example,

20+10*5=70

## Example on operator precedence

### Example 1

a=90 b=80 c=70 d=100 e=a+b*c/d print(e)

#### Output:

146.0

In the above expression, * has higher precedence than +, so it first multiplies 10 and 5 and then adds 20. However, if we want to change the order in which operators are evaluated, we can use parentheses.

Parentheses can change the order in which an operator is applied. The operator in the parentheses is applied first, even if there is a higher priority operator in the expression.

For example,

(40+20)*30/10=180

### Example 2

a=40 b=20 c=30 d=10 e=((a+b)*c)/d print(e)

#### Output:

180.0

## Example of Operator Associativity (Left-right)

A=200 B=10 C=10 D=A/B*C print(D)

### Output:

200.0

In the above example, A/B*C is calculated as (A/B)*C

## Example of Operator Associativity (Right-left)

a=3 b=2 c=2 d=a**b**c print(d)

#### Output:

81

## Leave a comment