DEV Community

hebaShakeel
hebaShakeel

Posted on

Operators in Python

Operators are used to perform operations on variables and values. Python has following operators:

Arithmetic Operators

x = 5
y = 2
print(x + y)
o/p = 7

print(x - y)
o/p = 3

print(x * y)
o/p = 10

print(x / y)
o/p = 2.5

print(x % y)
o/p = 1

print (x ** 2) power of op
o/p = 25

print ( x // 2) performs integer division
o/p = 2

Comparison Operators

print(x > y)
o/p = True

print(x < y)
o/p = False

print(x >= y)
o/p = True

print(x <= y)
o/p = False

print(x == y)
o/p = False

print(x != y)
o/p = True

Logical Operators

x = True
y = False

print(x or y)
o/p = True

print(x and y)
o/p = False

print(not x)
o/p = False

print(not y)
o/p = True

Bitwise Operators

They work on binary values

x = 2
y = 3

print(x & y)
o/p = 2

binary of 2 = 010
binary of 3 = 011
performing bitwise and on 010 and 011, we get 010 (2 in decimal)

print(x | y)
o/p = 3
performing bitwise or on 010 and 011, we get 011 (3 in decimal)

print (x >> 2)
o/p = 0

print (y << 3)
o/p = 24

print (~x) # 1s complement
o/p = -3

Assignment Operators

a = 3
print (a)
o/p = 3

a += 3
o/p = 6

a =- 3
o/p = 3

a *= 3
o/p = 9

a &= 3

a++ and ++a does not exist in Python. Using this generates a Syntax Error.

Identity Operators

Checks if 2 variables are on the same memory location.

a = 3
b = 3

print (a is b)
o/p = True

a = [1,2,3]
b = [1,2,3]

print(a is b)
o/p = False

print(a is not b)
o/p = True

Membership Operator

x = "Delhi"

print("D" in x)
o/p = True

print ("D" not in x)
o/p = False

x = [1,2,3]
print(5 in x)
o/p = False

Top comments (0)