Precedence Of Operator's in Python
2 min readMar 1, 2021
When an expression or statement involves multiple operators, python resolves the order of execution through Operator Precedence.
Here We will see the list of highest precedence to lowest of all the operators in python.
Example 1:
>>> 2**3*2
16
>>> 2**(3*2)
64
- In the above code in the first statement as **(exponentiation) is executed first as it has highest precedence than *(Multiplication)
- Next statement ( ) has highest precedence than remaining hence it is executed first.
Example 2:
>>> ~3+1
-3
>>> ~(3+1)
-5
- In the first statement ~ (Bitwise not) is executed first
- Second statement ( ) is executed first, 3+1 is performed first and later bitwise not applied to 4.
Example 3:
>>> 100*2/5//2%3
2.0
- If all the operators have equal precedence then it executes from left to right. In the above statement first 100*2 calculated 200.
- Later it is divided by 5 which is equal to 40.0
- Later floor division done on 40.0 with 2 which is equal to 20.0
- Later Modulo is applied between 20.0 % 3 which is equal to 2.
Example 4:
>>> 20+3*4
32
>>> 20-3*4
8
- In the first statement *(Multiply) has high precedence than +(Addition) hence 3*4 calculated first.
Example 6:
>>> 0|1&1^1
0
>>> 0|1&0^1
1
- In the first statement 1&1 is calculated which is 1, Later 1|1 calculated which is 0, Later 0|0 calculated which is 0.
- In the second statement 1&0 calculated which is 0,Later 0(Bitwise XOR) 1 calculated which is 1,Later 0|1 calculated which is 1.
Example 7:
>>> not 7>8 and 6<8 or 1!=2
True
- not 7>8 and 6<8 or 1!=2==>not False and True or True
- not False and True or True==>True and True or True
- True and True or True==>True or True
- True or True==>True
Example 8:
>>> 2 in [1,2,3,4] and True or not False
True
- 2 in [1,2,3,4] and True or not False==> True and True or not False
- True and True or not False==>True and True or True
- True and True or True==>True or True
- True or True==> True
>>> 5 in [1,2,3,4] and True or not True
False
- 5 in [1,2,3,4] and True or not True==> False and True or not True
- False and True or not True==>False and True or False
- False and True or False==>False or False
- False or False==> False