In Python, operators are special symbols or keywords that are used to perform operations on operands. Operands can be variables, values, or expressions. Python supports various types of operators, including arithmetic operators, comparison operators, logical operators, assignment operators, and more. Let's go through each type of operator with examples:
Example:
a = 10
b = 3
print(a + b) # Output: 13
print(a - b) # Output: 7
print(a * b) # Output: 30
print(a / b) # Output: 3.3333333333333335
print(a % b) # Output: 1
print(a // b) # Output: 3
print(a ** b) # Output: 1000
Example:
x = 5
y = 10
print(x == y) # Output: False
print(x != y) # Output: True
print(x < y) # Output: True
print(x > y) # Output: False
print(x <= y) # Output: True
print(x >= y) # Output: False
Example:
x = True
y = False
print(x and y) # Output: False
print(x or y) # Output: True
print(not x) # Output: False
Example:
a = 10
a += 5 # Equivalent to: a = a + 5
print(a) # Output: 15
Example:
x = [1, 2, 3]
y = [1, 2, 3]
print(x is y) # Output: False
print(x is not y) # Output: True
Example:
my_list = [1, 2, 3]
print(1 in my_list) # Output: True
print(4 not in my_list) # Output: True
These are some of the commonly used operators in Python. Understanding and using operators effectively is essential for writing concise and efficient code.