# Python Operators

Operators are used to performing a specific operation on variables and values. Python has a lot of operators that are either keywords or special characters. The values or variables on which these operators work are called operands.

## Types of Python Operators

Python operators can be classified into the following categories.

1. Arithmetic Operators
2. Logical Operators
3. Comparison Operators
4. Bitwise Operators
5. Assignment Operators
6. Membership Operators
7. Identity Operators

### 1. Arithmetic Operators

Arithmetic operators usually work on numbers. There are operators for addition, subtraction, multiplication, division, modulus, and exponential operations. Some of these operators work for strings too. All the arithmetic operators are special characters.

• – : subtraction operator
• * : multiplication operator
• / : division operator
• ** : exponential operator
• // : floor division operator

Let’s look at an example of arithmetic operators in Python.

```x = 15
y = 7

sum = x + y

subtraction = x - y
print("subtraction =", subtraction)

multiplication = x * y
print("multiplication =", multiplication)

division = x / y
print("division =", division)

modulus = x % y
print("modulus =", modulus)

exponent = x ** 2
print("exponent =", exponent)

floor_division = x // y
print("division =", floor_division)  # 2
```

Output:

Python supports addition and multiplication operators for strings.

```print("addition of strings =", ("Python" + " " + "Operators"))
print("multiplication of strings =", ("Python" * 2))
```

Output:

```addition of strings = Python Operators
multiplication of strings = PythonPython
```

### 2. Comparison Operators

Comparison operators are used to compare two values. The result is always a boolean value – `True` or `False`.

The list of comparison operators in Python is:

• == : returns True if both the values are equal.
• != : returns True if both the operands are not equal.
• > : returns True if the left operand is greater than the right operand.
• < : returns True if the left operand is less than the right operand.
• >= : returns True if the left value is greater than or equal to the right value.
• <= : returns True if the left value is less than or equal to the right value.

Let’s look at an example to use comparison operators in Python.

```x = 10
y = 20

print(f'equals = {x == y}')
print(f'not equals = {x != y}')
print(f'greater than = {x > y}')
print(f'less than = {x < y}')
print(f'greater than or equal to = {x >= y}')
print(f'less than or equal to = {x <= y}')
```

Output:

These operators work on strings too. A string is considered greater than another string if it comes after that lexicographically. For example, “Hi” is greater than “Hello” in lexicographically comparison.

### 3. Bitwise Operators

They are also called binary operators and they work on integers only. The operand values are converted to binary and then the operation is perform on every bit. Finally, the value is converted back to decimal and returned.

There are 6 bitwise operators in Python.

• & : Bitwise AND operator
• | : Bitwise OR operator
• ^ : Bitwise XOR operator
• ~ : Binary ones’ complement operator
• << : Binary left shift operator
• >> : Binary right shift operator
```x = 10  # 1010
y = 4  #  0100

print(f'Binary AND = {x & y}')
print(f'Binary OR = {x | y}')
print(f'Binary XOR = {x ^ y}')
print(f'Binary Ones Complement = {~x}')
print(f'Binary Left Shift by 2 = {x << 2}')
print(f'Binary Right Shift by 3 = {x >> 3}')
```

Output:

```Binary AND = 0
Binary OR = 14
Binary XOR = 14
Binary Ones Complement = -11
Binary Left Shift by 2 = 40
Binary Right Shift by 3 = 1
```

### 4. Python Logical Operators

There are three logical operators in Python. They work with boolean operands and return a boolean value. They are made of reserved keywords in Python.

• and : logical AND operator
• or : logical OR operator
• not : logical NOT operator
```b1 = True
b2 = False

print(f'{b1} and {b2} = {b1 and b2}')
print(f'{b1} and {b2} = {b1 or b2}')
print(f'not {b1} = {not b1}')
```

Output:

### 5. Assignment Operators

Assignment operator (=) is used to assign the left operand value to the right operand.

There are some compound assignment operators to perform some arithmetic operation between the two operands and then assign the value to the left operand.

• = : simple assignment operator
• += : adds the two operands and then assign the value to the right operand
• -= : subtracts the right operand from the left and then assign the value to the left operand
• *= : multiplies both the operands and then assign to the left
• /= : divides left operand from the right operand and then assign the value to the left operand
• %= : modulus of left and right operands and then assigned to the left operand
• **= : exponential of left to the right operands and then assignment to the left operand
• //= : floor division of the left and right operands and then the value is assigned to the left operand
```a = 10  # simple assignment operator
b = 5

a += b  # same as a=a+b
print(a)  # 15

a -= b  # same as a=a-b
print(a)  # 10

a *= b  # same as a = a*b
print(a)  # 50

a /= b  # same as a = a/b
print(a)  # 10.0

a %= b  # same as a = a%b
print(a)  # 0.0

a = 2
b = 4

a **= b  # same as a = a**b
print(a)  # 16

a //= b  # same as a = a // b (floor division)
print(a) # 4
```

### 6. Membership Operators

Membership operators are used to checking the presence of a value in a sequence. There are two membership operators in Python.

1. in
2. not in

These operators are generally used with if-else condition.

```x = 3

my_tuple = (1, 2, 3, 4)
my_list = [1, 2, 3, 4]
my_str = "Hello"

print(f'{x} is present in {my_tuple} = {x in my_tuple}')

if x in my_list:
print(f'{x} is present in {my_list}')

if 'a' not in my_str:
print(f'a is not present in {my_str}')
```

### 7. Identity Operators

Python identity operators are used to check if two variables point to the same memory location or not. There are two identity operators.

1. is : returns True if both the variables point to the same memory location
2. is not : returns True if both the variables point to the different memory location
```s1 = [1, 2]
s2 = [1, 2]
s3 = s1

print(s1 is s2)  # False
print(s1 is s3)  # True

print(s1 is not s2)  # True
print(s1 is not s3)  # False
```

## Operator Precedence in Python

Sometimes an expression contains multiple operators. In that case, operator precedence is used to determine the order of execution.

• We can create a group of expression using parenthesis. The expression in the parenthesis is evaluated first before they can take part in further calculations.
• Some operators have the same level of precedence. In this case, the expression is evaluated from the left to right.

Below table lists the operators precedence in the decreasing order.

Operator Precedence (Decreasing Order)
** (Exponent)
~ (Ones’ Complement)
*, /, //, % (Multiply, Divide, Floor Division, Modulus Operators)
<<, >> (right and left shift operators)
& (Bitwise AND)
|, ^ (Bitwise OR, XOR)
==, !=, >, <, >=, <= (Comparison Operators)
=, +=, -=, *=, /=, //=, %= (Assignment Operators)
is, is not (Identity Operators)
in, not in (Membership Operators)
not, and, or (Logical Operators)

Let’s see what happens when an operator is not supported for a class.

```class Data:
id = 0

def __init__(self, i):
self.id = i

d1 = Data(10)
d2 = Data(20)

d3 = d1 + d2
print(d3.id)
```

Output:

```Traceback (most recent call last):
File "/Users/pankaj/Documents/PycharmProjects/PythonTutorialPro/hello-world/operators_examples.py", line 9, in <module>
d3 = d1 + d2
TypeError: unsupported operand type(s) for +: 'Data' and 'Data'
```

If we have to support + operator for Data class, we have to define __add__() method for it. Let’s see the updated code and the output.

```class Data:
id = 0

def __init__(self, i):
self.id = i

return Data(self.id + other.id)

d1 = Data(10)
d2 = Data(20)

d3 = d1 + d2
print(d3.id)
```

Output: 30

Below table provide the methods to override to overload an operator in Python.

OperatorDescriptionMethod
Subtraction__sub__(self, other)
*Multiplication__mul__(self, other)
/True Division__truediv__(self, other)
//Floor Division__floordiv__(self, other)
%Remainder__mod__(self, other)
**Power__pow__(self, other)
&Bitwise AND__and__(self, other)
|Bitwise OR__or__(self, other)
^Bitwise XOR__xor__(self, other)
>Greater than__gt__(self, other)
>=Greater than or equal to__ge__(self, other)
<Less than__lt__(self, other)
<=Less than or equal to__le__(self, other)
==Equal to__eq__(self, other)
!=Not equal to__ne__(self, other)

## Python operator Module

Python operator module provides a set of functions corresponding to the operators in Python. These function names are same as special methods, without the double underscores.

Let’s look at an example of a custom class that supports operators – +, >, and *. We will use operator module functions to call these methods on the objects of the class.

```import operator

class Data:
id = 0

def __init__(self, i):
self.id = i

return Data(self.id + other.id)

def __gt__(self, other):
return self.id > other.id

def __mul__(self, other):
return Data(self.id * other.id)

d1 = Data(10)
d2 = Data(20)

print(d3.id)

d3 = operator.mul(d1, d2)
print(d3.id)

flag = operator.gt(d1, d2)
print(flag)
```

## Conclusion

Python supports a lot of operators to help us in common arithmetic, comparison, assignment, binary, or logical operations. The best part is that many of these operators can be overloaded by defining special methods in our class. If you want your program to look more object-oriented, you can use the operator module that provides functions corresponding to these operators.