What Are Operators?
Operators are special symbols in Python that perform operations on values and variables (called operands). Python supports several categories: arithmetic, comparison, logical, assignment, membership, identity, and bitwise.
Arithmetic Operators
Used to perform mathematical calculations:
a = 10
b = 3
print(a + b) # 13 → Addition
print(a - b) # 7 → Subtraction
print(a * b) # 30 → Multiplication
print(a / b) # 3.333... → Division (always returns a float)
print(a // b) # 3 → Floor Division (drops the decimal)
print(a % b) # 1 → Modulus (remainder)
print(a ** b) # 1000 → Exponent (a raised to the power b)
Comparison Operators
Compare two values and return a Boolean (True / False):
a = 10
b = 20
print(a == b) # False → Equal to
print(a != b) # True → Not equal to
print(a > b) # False → Greater than
print(a < b) # True → Less than
print(a >= b) # False → Greater than or equal to
print(a <= b) # True → Less than or equal to
Logical Operators
Combine multiple conditions together:
age = 20
has_id = True
print(age >= 18 and has_id) # True → both conditions must be True
print(age >= 18 or has_id) # True → at least one must be True
print(not has_id) # False → reverses the Boolean
Assignment Operators
Assign values to variables, often combined with an operation:
x = 10
x += 5 # same as x = x + 5 → 15
x -= 3 # same as x = x - 3 → 12
x *= 2 # same as x = x * 2 → 24
x /= 4 # same as x = x / 4 → 6.0
x //= 2 # same as x = x // 2 → 3.0
x **= 2 # same as x = x ** 2 → 9.0
x %= 4 # same as x = x % 4 → 1.0
Membership Operators
Check whether a value exists inside a sequence (list, string, tuple, etc.):
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("mango" not in fruits) # True
Identity Operators
Check whether two variables point to the exact same object in memory (not just equal values):
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == c) # True → same values
print(a is c) # True → same object in memory
print(a is b) # False → equal values, but different objects
Bitwise Operators
Operate directly on the binary representation of integers:
a = 6 # 0110
b = 3 # 0011
print(a & b) # 2 → AND
print(a | b) # 7 → OR
print(a ^ b) # 5 → XOR
print(~a) # -7 → NOT
print(a << 1) # 12 → Left Shift
print(a >> 1) # 3 → Right Shift
Operator Precedence
When an expression has multiple operators, Python follows a strict order of evaluation — parentheses first, then exponents, then multiplication/division, then addition/subtraction:
result = 10 + 2 * 3
print(result) # 16, not 36 — multiplication happens before addition
result = (10 + 2) * 3
print(result) # 36 — parentheses override the default order
Key Takeaways
- Arithmetic operators handle math; comparison operators return True/False
- Logical operators (
and,or,not) combine conditions ==checks equal values, whileischecks the same object in memory- When unsure of evaluation order, use parentheses to make your intent explicit