Operators in Python
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Python language is rich in built-in operators and provides following types of operators.
Types of Operators
We have the following types of operators in Python programming −
Arithmetic operators
Assignment operators
Relational/Comparison Operators
Logical Operators
Bitwise Operators
Identity Operator
Membership Operator
Arithmetic Operator
Arithmetic operators are used with numeric values to perform common mathematical operations:
a=int(input("Enter First Number:"))
b=int(input("Enter First Number:"))
print("Addition:",a+b)
print("Subtraction:",a-b)
print("Multiplication:",a*b)
print("Division",a/b)
print("Floor Division:",a//b)
print("Modulus",a%b)
print("Exponentiation:",a**b)
Enter First Number:5
Enter First Number:2
Addition: 7
Subtraction: 3
Multiplication: 10
Division 2.5
Floor Division: 2
Modulus 1
Exponentiation: 25
Python Assignment Operators
Assignment operators are used to assign values to variables:
a = 10
print(a)
10
a = 10
b = 20
a = a + b
print(a)
30
a = 10
b = 20
a += b
print(a)
30
Python Comparison/Relational Operators
Comparison operators are used to compare two values:
a=10
b=20
c = a < b
print(c)
True
a=10
b=20
c = a > b
print(c)
False
a=10
b=20
c = a <= b
print(c)
True
a=10
b=20
c = a >= b
print(c)
False
a=10
b=20
c = a == b
print(c)
False
a=10
b=20
c = a != b
print(c)
True
Python Logical Operators
Logical operators are used to combine conditional statements:
Logial AND
x = 1
print(x < 5 and x < 10)
True
print(10 and 20)
20
Logical OR
x = 1
print(x < 5 or x > 4)
True
print(10 or 20)
10
Logical NOT
x = 1
print(not(x < 5 or x > 4))
False
a=0
print(not a)
True
Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
a=10
b=6
print("Bitwise AND:",a&b)
print("Bitwise OR:",a|b)
print("Bitwise XOR:",a^b)
print("Left Shift:",a<<2)
print("Right Shift:",a>>2)
print("1's Complement:",~a)
Bitwise AND: 2
Bitwise OR: 14
Bitwise XOR: 12
Left Shift: 40
Right Shift: 2
1's Complement: -11
Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:
l1=[1,2,3]
l2=[1,2,3]
print(l1==l2)
print(l1 is l2)
True
False
l3=l2
print(l2)
print(l3)
print(l2==l3)
print(l2 is l3)
[1, 2, 3]
[1, 2, 3]
True
True
del l2
print(l3)
[1, 2, 3]
Membership Operators
Membership operators are used to test if a sequence is presented in an object:
in - Evaluates to true if it finds a variable in the specified sequence
not in - Evaluates to true if it does not finds a variable in the specified sequence
L=[12,353,545,2,45,67,89,23]
n=2
print(n in L)
True
print(n not in L)
False
Top comments (0)