Quick summary
Summarize this blog with AI
An expression produces a value; operators help combine its operands. Choose the operation for the objects you actually have: numbers, strings, sets, and pandas Series can give the same symbol different meanings. These examples use Python 3.12.14; the pandas example is checked with pandas 2.2.3 and 3.0.6.
Predict precedence and arithmetic before using a result
print(2 + 3 * 4, (2 + 3) * 4)
print(-2 ** 2, (-2) ** 2, 2 ** 3 ** 2)
print(7 / 2, 7 // 2, -7 // 2, -7 % 2)
print("ab" * 2, [1] + [2])
Expected output:
14 20
-4 4 512
3.5 3 -4 1
abab [1, 2]
Multiplication binds before addition. Exponentiation groups from the right, and -2 ** 2 negates the squared result. Floor division rounds down, including for negatives; it is not truncation toward zero. With a positive divisor, the displayed negative dividend has a nonnegative remainder. Division by zero remains an error.
| Task | Expression | Important boundary |
|---|---|---|
| Value equality | a == b | May be elementwise for arrays. |
| Same object | a is b | Use for identity, especially None, not numeric equality. |
| Scalar conjunction | a and b | Returns an operand and short-circuits. |
| Elementwise conjunction | (s > 0) & (s < 10) | Parenthesize each comparison. |
| Assignment | x = value | A statement; == compares. |
Compare values, identities, and approximate numbers deliberately
import math
left = [1, 2]
right = [1, 2]
print(left == right, left is right)
print(1 < 2 < 3)
print(0.1 + 0.2 == 0.3, math.isclose(0.1 + 0.2, 0.3))
print([] and "unused", "present" or "fallback")
Expected output:
True False
True
False True
[] present
A chained scalar comparison tests adjacent relationships. Do not transfer that syntax unchanged to a Series, whose truth value is ambiguous. For approximate floating-point calculations, choose tolerances appropriate to the scale; default isclose settings are not a domain policy, especially near zero. Exact money calculations usually need an explicit decimal or integer-unit contract.
Filter pandas rows with elementwise conditions
import pandas as pd
frame = pd.DataFrame({"amount": pd.array([0, 5, 12, None], dtype="Int64"),
"status": ["paid", "paid", "paid", "paid"]})
mask = (frame["amount"] > 0) & (frame["amount"] < 10)
print(mask.fillna(False).tolist())
print(frame.loc[mask.fillna(False), "amount"].tolist())
try:
(frame["amount"] > 0) and (frame["status"] == "paid")
except ValueError:
print("and requires one truth value, not a Series")
Expected output:
[False, True, False, False]
[5]
and requires one truth value, not a Series
The missing amount yields an unknown nullable Boolean before fillna(False). This report deliberately excludes unknown amounts; it does not prove they are nonpositive. &, |, and ~ operate elementwise here. They are bitwise operators on integers and do not provide scalar short-circuit guards. Parentheses prevent their precedence from binding to the wrong operands.
Read overloaded operations in context
List + concatenates, numeric + adds, and custom classes can define their own behavior. Augmented assignment such as += can mutate a list but rebind an integer name. Use small counterexamples when a result surprises you: a negative number, empty collection, missing value, and equal-but-distinct object expose different mistakes. Never use eval to interpret an untrusted expression as a shortcut for validating input.
References and next steps
Python expressions and precedence, pandas Boolean indexing, Identity versus equality.