In Python, operators are special symbols and keywords used to evaluate mathematical computations, compare values, assign variables, and manipulate binary data.
Seven Core Operator Groups: Python classifies operators into arithmetic, relational comparison, assignment, logical, identity (is / is not), membership (in / not in), and bitwise operators. To inspect evaluation hierarchy and PEMDAS execution rules, see operator precedence. For object identity addresses, see id().
Arithmetic operators execute numeric computations. Python differentiates true division (/), which always produces floats, from floor division (//):
| Operator | Operation | Description & Example |
|---|---|---|
+, - | Addition / Subtraction | 4 + 5 = 9, 10 - 4 = 6 |
*, / | Multiplication / True Division | 6 * 7 = 42, 29 / 5 = 5.8 (always float) |
//, % | Floor Division / Modulus | 29 // 5 = 5, 29 % 5 = 4 |
** | Exponentiation | 3 ** 4 = 81 |
# 1. Arithmetic Operators & Division Precision
a, b = 29, 5
print("True Division (/): ", a / b) # Float division
print("Floor Division (//): ", a // b) # Discards fractional remainder
print("Modulus (%): ", a % b) # Division remainder
print("Exponentiation (**): ", a ** 2)
print("Negative Floor: ", -29 // 5) # Floors down toward negative infinityTerminal Output:
True Division (/): 5.8
Floor Division (//): 5
Modulus (%): 4
Exponentiation (**): 841
Negative Floor: -6
Comparison operators evaluate conditions and always return a boolean: True or False. Python supports chained comparisons such as x < y < z:
| Operator | Meaning | Example | Result |
|---|---|---|---|
==, != | Equality / Inequality | 5 == 5, 5 != 6 | True |
>, < | Greater / Less than | 10 > 5, 5 < 10 | True |
>=, <= | Greater / Less or Equal | 10 >= 10, 3 <= 5 | True |
# 2. Comparison & Chained Relational Operators
x, y, z = 15, 25, 35
print("Equality (==): ", x == 15)
print("Inequality (!=): ", x != y)
print("Greater than (>): ", y > x)
print("Chained comparison:", x < y < z) # Evaluates as: x < y and y < zTerminal Output:
Equality (==): True
Inequality (!=): True
Greater than (>): True
Chained comparison: True
Assignment operators bind values to variables. Compound operators perform arithmetic and assignment in one step:
| Operator | Equivalent Syntax | Description |
|---|---|---|
+=, -= | x += 5, x -= 5 | Addition & subtraction assignment |
*=, /= | x *= 2, x /= 2 | Multiplication & true division assignment |
//=, %= | x //= 2, x %= 2 | Floor division & modulus remainder assignment |
**=, := | x **= 3, (n := len(s)) | Power assignment & walrus expression |
# 3. Assignment & Compound Operators
count = 100
count += 25 # Equivalent to: count = count + 25
count *= 2 # Equivalent to: count = count * 2
print("Calculated count:", count)
# Walrus Operator (:=) assigns within expressions (Python 3.8+)
if (n := len("plus2net")) > 5:
print(f"String length {n} is greater than 5")Terminal Output:
Calculated count: 250
String length 8 is greater than 5
Python provides three logical operators: and, or, and not. These operators use short-circuit evaluation, returning the operand that finalized the decision:
x and y: Returns x if x is false; otherwise returns y.x or y: Returns x if x is true; otherwise returns y.not x: Inverts truth value (returns True if x is falsy).# 4. Logical Operators & Short-Circuit Evaluation
is_admin, is_verified = True, False
print("AND (and):", is_admin and is_verified)
print("OR (or): ", is_admin or is_verified)
# Short-circuiting: returns the determining operand directly
user_role = None
active_role = user_role or "Guest"
print("Fallback role:", active_role)Terminal Output:
AND (and): False
OR (or): True
Fallback role: Guest
Identity operators (is, is not) check memory address identity (id()), while membership operators (in, not in) test presence inside containers:
| Operator | Category | Condition Evaluated |
|---|---|---|
is, is not | Identity | id(a) == id(b) (exact memory address) |
in, not in | Membership | Checks presence in sequence or dict keys (O(1) in sets/dicts) |
# 5. Identity (is) vs Equality (==) & Membership (in)
lst1 = [1, 2, 3]
lst2 = [1, 2, 3]
lst3 = lst1
print("lst1 == lst2 (Value equality): ", lst1 == lst2)
print("lst1 is lst2 (Memory identity): ", lst1 is lst2)
print("lst1 is lst3 (Shared reference):", lst1 is lst3)
frameworks = ["Django", "FastAPI", "Flask"]
print("'FastAPI' in list: ", "FastAPI" in frameworks)Terminal Output:
lst1 == lst2 (Value equality): True
lst1 is lst2 (Memory identity): False
lst1 is lst3 (Shared reference): True
'FastAPI' in list: True
Bitwise operators manipulate integers at the individual binary bit level. Learn more in our bitwise operators guide:
| Operator | Name | Description |
|---|---|---|
&, | | Bitwise AND / OR | 12 & 5 = 4 (0b0100), 12 | 5 = 13 (0b1101) |
^, ~ | Bitwise XOR / NOT | 12 ^ 5 = 9, ~12 = -13 (equals -(x + 1)) |
<<, >> | Bit Shifts | 12 << 1 = 24 (multiply 2), 12 >> 1 = 6 (divide 2) |
# 6. Bitwise Operators & Binary Masks
# 12 = 0b1100, 5 = 0b0101
p, q = 12, 5
print("Bitwise AND (&): ", p & q, "-> bin:", bin(p & q))
print("Bitwise OR (|): ", p | q, "-> bin:", bin(p | q))
print("Bitwise XOR (^): ", p ^ q, "-> bin:", bin(p ^ q))
print("Left Shift (<<):", p << 1, "-> bin:", bin(p << 1))Terminal Output:
Bitwise AND (&): 4 -> bin: 0b100
Bitwise OR (|): 13 -> bin: 0b1101
Bitwise XOR (^): 9 -> bin: 0b1001
Left Shift (<<): 24 -> bin: 0b11000
Practical implementation patterns for binary permission masks and config fallbacks:
# 7. Production Recipes: Flags & Config Resolution
READ_PERM = 1 << 0 # 1 (0b001)
WRITE_PERM = 1 << 1 # 2 (0b010)
user_perms = READ_PERM | WRITE_PERM
has_write = bool(user_perms & WRITE_PERM)
print("User has Write Permission:", has_write)
def resolve_port(env_p: int, conf_p: int) -> int:
return env_p or conf_p or 5432
print("Resolved DB Port: ", resolve_port(0, 3306))Terminal Output:
User has Write Permission: True
Resolved DB Port: 3306
Watch out for floating point rounding, identity vs equality confusion, and in-place mutation side-effects:
# 8. Common Operator Pitfalls
# Trap 1: Floating-point precision
print("0.1 + 0.2 == 0.3: ", 0.1 + 0.2 == 0.3)
print("0.1 + 0.2 raw result:", 0.1 + 0.2)
# Trap 2: True == 1 equality match
print("True == 1 (Equality):", True == 1)
print("True is 1 (Identity):", True is 1)Terminal Output:
0.1 + 0.2 == 0.3: False
0.1 + 0.2 raw result: 0.30000000000000004
True == 1 (Equality): True
True is 1 (Identity): False
Practice operator calculations, binary masking, and short-circuit logic in our interactive companion Jupyter Notebook:
Explore interactive code cells covering all operator categories, test chained comparisons, and run self-validating unit assertions.
View on GitHub Run in Google ColabRun these unit checks directly in Python or your local environment to verify operator behaviors:
# 9. Self-verifying unit test suite for Python Operators
assert 10 + 5 == 15 and 10 - 4 == 6
assert 7 * 6 == 42 and 20 / 4 == 5.0
assert 17 // 3 == 5 and 17 % 3 == 2 and 2 ** 5 == 32
assert (5 < 10 < 15) is True and (10 >= 10) is True
assert ("default" or "fallback") == "default"
assert ("" or "fallback") == "fallback"
a, b = [100], [100]
assert a == b and a is not b
d = {"token": "xyz"}
assert "token" in d and "xyz" not in d
print("All Python Operator unit assertions successfully verified!")Terminal Output:
All Python Operator unit assertions successfully verified!
== compares whether two objects have equal values, whereas is compares whether two variables share the exact same memory address (id(a) == id(b)).
In Python 3, single slash / is true division, always returning a float. To perform integer truncation division, use double slash 29 // 5.
In a or b, if a evaluates to true, Python immediately returns a without evaluating b. In a and b, if a is false, Python immediately returns a.
Introduced in Python 3.8, the assignment expression operator := allows you to assign a variable within an expression, such as in an if condition or while loop test.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.