Operators are special symbols that designate logical computations and are used to manipulate the value and the variables upon which it basically acts and then returns a result.
Let’s look at the types of operators in Python:
Arithmetic Operators
Basic mathematical operations like addition(+) ,subtraction(-) , multiplication(*) or division(/) are performed with the help of arithmetic operators.
Example 1
a = 1 | |
b = 2 | |
print(a + b) |
3
Example 2
a = 3 | |
b = 2 | |
print(a * b) |
6
Assignment Operators
Values are designated to variables with the help of Assignment Operators.
Example 1
a = 3 | |
print(a) |
3
here the value 3 has been assigned to a.
Example 2
a = 3 | |
a += 4 | |
print(a) |
7
a += 4 is the same as a = a + 4.
Comparison Operators
They are used to compare values and establish a correspondence between them.
Example 1
a = 1 | |
b = 2 | |
print(a == b) |
False
Example 2
a = 1 | |
b = 2 | |
print(a > b) |
False
Example 3
a = 1 | |
b = 2 | |
print(a <= b) |
True
Logical Operators
Logical Operators are used to combine conditional statements like:
– And
– Or
– Not
AND Logical Operator
In this case, all the statements have to be true.
a = 11 | |
b = 2 | |
print(a == 1 and b == 2) |
False
OR Logical Operator
In this case, at least one of the statements has to be true
a = 1 | |
b = 2 | |
print(a == 1 or b == 4) |
True
NOT Logical Operator
The result is the opposite as in, if the statement is true, it returns false and vice-versa.
a = 1 | |
print(a != 1) |
True
Identity Operators
Identity operators are used to check if 2 variables have the same memory location.
a = ["a", "b", "c"] | |
b = ["a", "b", "c"] | |
print(a is b) |
False
Here, a and b have the same content but are 2 variables with 2 different memory locations and therefore, are not the same object.
Membership Operators
To check if a variable exists inside a list/tuple/set, membership operators are used.
a = [1, 2, 3] | |
print(2 in a) |
True