7. Python Operators Explained with Examples
Operators in Python are special symbols used to perform operations on variables and values. Whether you are performing calculations, comparing values, or building logical conditions, operators are essential in every Python program.
1) Arithmetic Operators
Arithmetic operators are used to perform mathematical operations.
a = 10
b = 3
print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # Division
print(a % b) # Modulus (remainder)
print(a ** b) # Power (exponent)
print(a // b) # Floor division
2) Comparison Operators
Comparison operators compare two values and return True or False.
x = 5
y = 10
print(x == y) # Equal
print(x != y) # Not equal
print(x > y) # Greater than
print(x < y) # Less than
print(x >= y) # Greater or equal
print(x <= y) # Less or equal
3) Logical Operators
Logical operators combine multiple conditions.
age = 20
is_student = True
print(age > 18 and is_student)
print(age > 25 or is_student)
print(not is_student)
- and → True if both conditions are True
- or → True if at least one condition is True
- not → Reverses the result
4) Assignment Operators
Assignment operators assign values to variables.
number = 5
number += 2 # number = number + 2
number -= 1 # number = number - 1
number *= 3
number /= 2
5) Membership Operators
Membership operators check if a value exists in a sequence.
fruits = ["apple", "banana", "orange"]
print("apple" in fruits)
print("grape" not in fruits)
6) Identity Operators
Identity operators compare memory locations (not just values).
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a is b) # True
print(a is c) # False
print(a == c) # True
7) Bitwise Operators (Advanced)
Bitwise operators work at the binary level. These are more advanced but useful in low-level programming.
a = 5 # 0101
b = 3 # 0011
print(a & b) # AND
print(a | b) # OR
print(a ^ b) # XOR
print(~a) # NOT
print(a << 1) # Left shift
print(a >> 1) # Right shift
8) Operator Precedence
Python follows an order of operations similar to mathematics. For example:
result = 2 + 3 * 4
print(result) # 14, not 20
Use parentheses to control priority:
result = (2 + 3) * 4
print(result) # 20
Conclusion
Operators are the building blocks of logic and computation in Python. From arithmetic calculations to complex logical conditions, understanding operators helps you write cleaner and more powerful programs.
Practice combining different operators inside conditions and loops. Mastery of operators makes problem-solving much easier.