In Python, operators are symbols or keywords used to perform operations on values or variables. There are several types of operators in Python:
- Arithmetic operators: These are used to perform mathematical operations such as addition, subtraction, multiplication, division, modulus, exponentiation, and floor division.
Example:
a = 10 b = 5 print(a + b) # Output: 15 print(a - b) # Output: 5 print(a * b) # Output: 50 print(a / b) # Output: 2.0 print(a % b) # Output: 0 print(a ** b) # Output: 100000 print(a // b) # Output: 2
- Comparison operators: These are used to compare two values and return a Boolean value (True or False) based on the comparison. The comparison operators include ==, !=, >, <, >=, and <=.
Example:
a = 10 b = 5 print(a == b) # Output: False print(a != b) # Output: True print(a > b) # Output: True print(a < b) # Output: False print(a >= b) # Output: True print(a
- Logical operators: These are used to combine Boolean expressions and return a Boolean value. The logical operators include and, or, and not.
Example:
a = 10 b = 5 c = 7 print(a > b and b > c) # Output: False print(a > b or b > c) # Output: True print(not(a > b)) # Output: False
- Assignment operators: These are used to assign values to variables. The assignment operators include =, +=, -=, *=, /=, %=, **=, and //=.
Example:
a = 10 b = 5 a += b # Equivalent to a = a + b print(a) # Output: 15 a **= b # Equivalent to a = a ** b print(a) # Output: 759375
- Identity operators: These are used to compare the memory location of two objects. The identity operators include is and is not.
Example:
a = [1, 2, 3] b = [1, 2, 3] c = a print(a is b) # Output: False print(a is not b) # Output: True print(a is c) # Output: True
- Membership operators: These are used to check whether a value is a member of a sequence or not. The membership operators include in and not in.
Example: Membership operators are used to test whether a value is a member of a sequence (list, tuple, set, dictionary).
in (is a member of) not in (is not a member of)
7. Identity Operators: Identity operators are used to compare the memory location of two objects.
is (is the same object as) is not (is not the same object as)