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.
|()||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|
Example on operator precedence
a=90 b=80 c=70 d=100 e=a+b*c/d print(e)
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.
a=40 b=20 c=30 d=10 e=((a+b)*c)/d print(e)
Example of Operator Associativity (Left-right)
A=200 B=10 C=10 D=A/B*C print(D)
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)