Python operators are symbols and keywords that perform calculations, compare values, combine conditions, assign data, and test membership or identity. They appear in almost every Python program, from a simple calculator to a complete web application.
This guide explains arithmetic, comparison, assignment, logical, membership, identity, bitwise, and conditional operators. You will also learn precedence, chaining, short-circuit behavior, overloaded operators, and common mistakes that cause subtle bugs.
Review Python data types, booleans, and collections as needed.
What Is an Operator?
An operator acts on one or more operands:
total = 10 + 5The values 10 and 5 are operands, and + is the operator. Python defines operator behavior according to the operand types.
The official Python expressions reference describes the language rules. The operator module documentation exposes many operators as callable functions.
Arithmetic Operators
a = 10
b = 3
print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # True division
print(a // b) # Floor division
print(a % b) # Remainder
print(a ** b) # ExponentiationTrue Division
The / operator returns a floating-point result:
print(8 / 2)
print(7 / 2)Floor Division
// rounds the quotient toward negative infinity, not simply toward zero:
print(7 // 2)
print(-7 // 2)This distinction matters with negative values.
Modulo
The remainder operator is useful for parity and cycles:
number = 14
if number % 2 == 0:
print("Even")Exponentiation
square = 5 ** 2
cube = 5 ** 3Exponentiation has higher precedence than unary minus, so use parentheses when intention could be unclear.
String Operators
Strings support concatenation and repetition:
first_name = "Ana"
last_name = "Silva"
full_name = first_name + " " + last_name
separator = "-" * 20For dynamic text, f-strings are usually clearer than repeated concatenation. The f-string guide covers formatting.
Comparison Operators
age = 21
print(age == 21)
print(age != 18)
print(age > 18)
print(age < 30)
print(age >= 21)
print(age <= 65)Comparison expressions return True or False.
Chained Comparisons
score = 85
if 0 <= score <= 100:
print("Valid score")This is equivalent in meaning to checking both boundaries with and, while evaluating the middle expression only once.
Logical Operators
Python uses the keywords and, or, and not.
age = 25
has_ticket = True
can_enter = age >= 18 and has_ticket
needs_help = age < 18 or not has_ticketand
and requires both conditions to be truthy:
if username and password:
print("Credentials received")or
or succeeds when at least one condition is truthy:
if is_admin or is_owner:
print("Edit allowed")not
if not items:
print("The collection is empty")The booleans guide explains truthy and falsy values.
Short-Circuit Evaluation
Logical operators may stop before evaluating every operand:
user = None
if user is not None and user["active"]:
print("Active user")If user is not None is false, Python does not evaluate the dictionary access. This prevents an error.
Logical Operators Return Operands
and and or do not always return booleans:
display_name = nickname or full_name or "Anonymous"The expression returns the first truthy value, or the last value if all are falsy. Use this idiom only when falsy values should genuinely trigger the fallback.
Assignment Operators
total = 10
total += 5
total -= 2
total *= 3
total /= 2
total //= 2
total %= 4
total **= 2Augmented assignment updates a variable using its current value. With mutable objects, the behavior may modify the object in place depending on its type.
The Walrus Operator
The assignment expression operator := assigns a value as part of a larger expression:
while (line := input("Text, or quit: ")) != "quit":
print(line)Use it when it removes real repetition without making the condition harder to read.
Membership Operators
in and not in test membership:
roles = {"admin", "editor"}
print("admin" in roles)
print("guest" not in roles)With dictionaries, membership checks keys:
user = {"name": "Mia", "active": True}
print("name" in user)The in operator guide covers strings, lists, sets, dictionaries, generators, and custom classes.
Identity Operators
is and is not compare object identity:
result = None
if result is None:
print("No result")Do not use is as a replacement for equality:
first = [1, 2]
second = [1, 2]
print(first == second)
print(first is second)The lists have equal values but are different objects. See == versus is for details.
Bitwise Operators
Bitwise operators work with the binary representation of integers:
a = 0b1100
b = 0b1010
print(bin(a & b)) # AND
print(bin(a | b)) # OR
print(bin(a ^ b)) # XOR
print(bin(~a)) # NOT
print(bin(a << 1)) # Left shift
print(bin(a >> 1)) # Right shiftThey are useful for flags, masks, binary protocols, low-level data, and some optimization problems. Do not confuse & with logical and, or | with logical or.
Set Operators
Sets reuse several symbols for mathematical operations:
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # Union
print(a & b) # Intersection
print(a - b) # Difference
print(a ^ b) # Symmetric differenceThe Python sets guide explains these operations in practical scenarios.
Conditional Expression
Python's one-line conditional expression is sometimes called a ternary operator:
status = "adult" if age >= 18 else "minor"Use it for short, simple alternatives. A normal if statement is clearer for complex branches. The ternary operator guide provides examples.
Operator Precedence
Precedence determines which operation runs first:
result = 2 + 3 * 4
print(result)Multiplication runs before addition. Parentheses make intention explicit:
result = (2 + 3) * 4When an expression mixes arithmetic, comparison, and logical operators, use parentheses even if you know the precedence table. Readability is more important than compactness.
Unary Operators
number = 5
positive = +number
negative = -number
inverted = not True
bitwise_inverted = ~numberUnary operators act on one operand.
Operators with Different Types
The same operator can behave differently according to type:
print(2 + 3)
print("Py" + "thon")
print([1, 2] + [3, 4])This behavior is called operator overloading. Classes can define special methods such as __add__ and __eq__.
Custom Operator Behavior
class Vector:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def __add__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
print(Vector(1, 2) + Vector(3, 4))Return NotImplemented when the operation does not support the other type. Python may then try the reflected operation or raise TypeError.
Floating-Point Comparisons
print(0.1 + 0.2 == 0.3)Binary floating-point cannot represent every decimal exactly. Use math.isclose() for approximate comparison:
import math
print(math.isclose(0.1 + 0.2, 0.3))Select tolerances appropriate to the domain.
Division by Zero
def safe_divide(a: float, b: float) -> float:
if b == 0:
raise ValueError("divisor cannot be zero")
return a / bThe exception handling guide explains validation and error recovery.
Common Mistakes
- Using
=when a comparison requires==. - Using
isfor numbers or strings instead of equality. - Confusing
andwith&, ororwith|. - Forgetting that
/returns a float. - Assuming floor division truncates toward zero.
- Comparing floats with exact equality.
- Writing a long expression without parentheses.
- Using
oras a fallback when zero or empty text is valid. - Forgetting that dictionary membership checks keys.
Practical Example: Order Calculation
def calculate_order_total(
unit_price: float,
quantity: int,
is_member: bool,
) -> float:
if unit_price < 0 or quantity < 0:
raise ValueError("price and quantity cannot be negative")
subtotal = unit_price * quantity
discount_rate = 0.10 if is_member and subtotal >= 100 else 0
discount = subtotal * discount_rate
return subtotal - discount
print(calculate_order_total(30, 4, True))This example combines arithmetic, comparison, logical, and conditional operators.
Frequently Asked Questions
What is the difference between = and ==?
= assigns a value. == compares values.
What is the difference between and and &?
and is a logical operator with short-circuit behavior. & is a bitwise operator and is also overloaded by sets and some libraries.
When should I use is?
Use it for identity checks, especially is None. Use == for value equality.
Why does 0.1 + 0.2 not equal 0.3 exactly?
Many decimal fractions cannot be represented exactly in binary floating-point.
Can classes define operators?
Yes. Special methods such as __add__, __lt__, and __eq__ customize supported operations.
Conclusion
Python operators provide the language for calculations, comparisons, decisions, membership tests, identity checks, assignments, and binary manipulation. Learn each category through small examples and pay attention to the types of the operands.
Use parentheses for clarity, compare None with identity, treat floating-point equality carefully, and choose logical operators instead of bitwise symbols for ordinary conditions. Clear expressions are easier to test and maintain.






