A PEMDAS (Parenthesis, Exponential, Multiply, Division, Addition, Subtraction) rule is used for the precedence of operators in Python. Operators having the same priority are evaluated from left to right.
1. Python Arithmetic Operator
It is used for mathematical operations such as addition, subtraction, multiplication, and division, etc.
x = 10
y = 5
print('x + y =',x+y) #Addition
print('x - y =',x-y) #Substraction
print('x * y =',x*y) #Multiplication
print('x / y =',x/y) #Division
print('x // y =',x//y) #Floor Division
print('x ** y =',x**y) #Exponent
2. Python Comparison Operators
It is used to compare values between operands.
x = 121
y = 101
print('x > y is', x > y) # Greater than
print('x < y is', x < y) # Less than
print('x == y is', x == y) # Equal to
print('x != y is', x != y) # Not equal to
print('x >= y is', x >= y) # Greater than or equal to
print('x <= y is', x <= y) # Less than or equal to
Explanation:
x > y: Checks ifxis greater thany(True in this case).x < y: Checks ifxis less thany(False here).x == y: Checks ifxis equal toy(False here).x != y: Checks ifxis not equal toy(True here).x >= y: Checks ifxis greater than or equal toy(True here).x <= y: Checks ifxis less than or equal toy(False here).
3. Python Logical Operators
x = True
y = False
print('x and y is',x and y) #if both are true
print('x or y is',x or y) #if either one is true
print('not x is',not x) #returns the complement
4. Python Bitwise Operators
It is used to manipulate bit values
a = 6
b = 3
print ('a=',a,':',bin(a),'b=',b,':',bin(b)) c = 0
c = a & b
print ("result of AND is ", c,':',bin(c))
c = a | b
print ("result of OR is ", c,':',bin(c))
c = a ^ b
print ("result of EXOR is ", c,':',bin(c))
c = ~a
print ("result of COMPLEMENT is ", c,':',bin(c))
c = a << 2
print ("result of LEFT SHIFT is ", c,':',bin(c))
c = a>>2
print ("result of RIGHT SHIFT is ", c,':',bin(c))
5. Python Membership Operators
Test for membership in a sequence
a = 5
b = 10
list = [1, 2, 3, 4, 5 ]
if ( a in list ):
print ("Line 1 - a is available in the given list")
else:
print ("Line 1 - a is not available in the given list")
if ( b not in list ):
print ("Line 2 - b is not available in the given list")
else:
print ("Line 2 - b is available in the given list")
6. Python Identity Operators
It checks if values on either side of the equality operator point to the same object.
a = 14
b = 14
print ('Line 1','a=',a,':',id(a), 'b=',b,':',id(b))
if ( a is b ):
print ("Line 2 - a and b have same identity")
else:
print ("Line 2 - a and b do not have same identity")