Operators are used to manipulate Python code and variables, as well as to control the flow of the program. The operators in Python can be categorized into the following types: arithmetic, logical, comparison, assignment, bitwise, identity, and membership operators. This article explains the different types of operators in the Python programming language with examples. I highly recommend you get the “Python Crash Course Book” to learn Python.
Types of Operators
There are seven types of operators in Python.
- Arithmetic Operators
- Assignment Operators
- Comparison Operators
- Logical Operators
- Bitwise Operators
- Identity Operators
- Membership Operators
1. Arithmetic Operators
Arithmetic operators are used for basic mathematical operations.
# Addition print(21 + 5) # Subtraction print(21 - 5) # Multiplication print(21 * 5) # Division print(21 / 5) # Integer/Floor Division print(21 // 5) # Power/Exponential print(21 ** 5) # Modulus print(21 % 5)
26 16 105 4.2 4 4084101 1
2. Assignment Operators
Assignment operators are used to assigning values to variables. The assignment operators in Python are:
a = 21 a += 21 # Equal to a=a+21 a -= 21 # Equal to a=a-21 a *= 21 # Equal to a=a*21 a /= 21 # Equal to a=a/21 a %= 21 # Equal to a=a%21 a //= 21 # Equal to a=a//21 a **= 21 # Equal to a=a**21 a &= 21 # Equal to a=a&21 a |= 21 # Equal to a=a|21 a ^= 21 # Equal to a=a^21 a >>= 21 # Equal to a=a>>21 a <<= 21 # Equal to a=a<<21
3. Comparison Operators
Comparison operators are used to comparing two values. The output of comparison operators is True or False.
# Equal a == b # Not Equal a != b # Greater than a > b # Less than a < b # Greater than or equal to a >= b # Less than or equal to a <= b
4. Logical Operators
Logical operators are used to combine conditional statements. The logical operators are the following:
# and (if both statements are true than it returns True) a > 10 and a < 20 # or (if any one statement is true than it returns True) a > 10 or a < 20 # Reverse the result not(a > 10)
5. Bitwise Operators
These operators are used to perform bitwise calculations on integers. These operators are:
|Bitwise Operator||Name of Operator||Syntax|
|&||Bitwise AND||a & b|
||||Bitwise OR||a | b|
|^||Bitwise XOR||a ^ b|
|>>||Bitwise right shift||a>>|
|<<||Bitwise left shift||a<<|
6. Identity Operators
These operators are used to compare the objects if they are actually the same object with the same memory location. These operators are:
|is||This operator returns true if both variables are the same object.||a is b|
|is not||This operator returns true if both variables are not the same object.||a is not b|
7. Membership Operators
The membership operators are used to find that the sequence is present in the object. The membership operators are “in” and “not in“.
a = [5, 10, 15, 20, 25] print(5 in a) print(5 not in a) print(30 in a) print(30 not in a)
True False False True