Python Operators

A PEMDAS (Parenthesis, Exponential, Multiply, Division, Addition, Subtraction) rule is used for the precedence of operators in Python. Operators having same priority are evaluated from left to right.
-
Python Arithmetic Operator
It is used for mathematical operations such as addition, substraction, 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
-
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 is',x>=y) #Greater than equal to print('x <= y is',x<=y) #Less than equal to -
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
-
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))
-
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")
-
Python Identity Operators
It checks if values on either side of 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")