Python operators

Arithmetic operator

Addition + Subtraction - Multiplication * Division / Modulus % Exponent ** Floor Division //

Logical operator

i = 5 j = 6 if (i == 5) and (j > i): print ("hello") else: print ("bye") if ((i == 5) and (j > i)): print ("hello") else: print ("bye") if (i == j) or (i == 5): print ("I is 5 or I is J") else: print ("I is not 5 and I is not J")

Bitwise operator

AND & OR | XOR ^ Unary ~ (Flipping bits) LEFT Shift << Right Shift >>

Relational operator

i = 5 j = 6 k = i s1 = "hello" s2 = "world" s3 = "hello" if s1 == s2: print ("S1 and S2 are equal") else: print ("S1 and S2 are not equal") if s1 == s3: print ("S1 and S3 are equal") else: print ("s1 and S3 are not equal") if i < j: print ("I is less that J") else: print ("I is not less than J") if j > i: print ("J is greater than I") else: print ("J is not greater than I") if i == k: print ("I is equal to K") else: print ("I is not equal to K") if i <= j: print ("I is less than or equal to J") else: print ("I is not less than or equal to J") if j >= i: print ("J is greater than or equal to I") else: print ("J is not greater than or equal to I") if i != j: print ("I is not equal to j") else: print ("I is equal to j")

Assignment operators

x = 5 print (x) x -= 1 print (x) x = 4 x += 1 print (x) x = 3 x *= 2 print (x) x = 16 x /= 2 print (x) x = 20.0 x /= 2 print (x) x = 3 x **= 2 print (x)

Membership operators

arr = [1, 2, 3, 4, 5] a = 3 b = 7 if b in arr: print (b, " is in array") else: print (b, " is not in array") if a in arr: print (a, " is in array") else: print (a, " is not in array")

Identity operators (Compares if data have same memory location)

a = 20 b = 20 if a is b: print ("Identity of a and b is same (", a, ",", b, ")") else: print ("Identity of a and b is not same (", a, ",", b, ")") if id (a) is id (b): print ("Identity of a and b is same. Using ID function (", a, ",", b, ")") else: print ("Identity of a and b is not same. Using ID function (", a, ",", b, ")") a = 30 if a is not b: print ("Identity of a and b is not same (", a, ",", b, ")") else: print ("Identity of a and b is same (", a, ",", b, ")")

Comments