Conditionals and Boolean Expressions
An if/elif/else chain evaluates conditions in order and executes the first
truthy branch.
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C or below"
Order matters when conditions overlap.
Truth values
None, False, numeric zero, and empty containers are false by default. Most
other objects are true; user-defined classes may customize truth testing.
Use an explicit comparison when empty, zero, and missing have different meanings:
if records is None:
load_records()
elif not records:
report_empty_dataset()
Comparisons
==and!=compare values.isandis notcompare identity.inandnot intest membership.- Ordered comparisons can be chained:
lower <= value < upper.
Do not use is for numeric or string value comparison; interpreter object reuse
is not a semantic guarantee.
Short-circuit operators
and and or evaluate left to right and return one of their operands, not
necessarily a bool:
display_name = supplied_name or "anonymous"
safe_ratio = denominator and numerator / denominator
The second expression is evaluated only when needed. Use this for guards, but avoid compact expressions whose mixed return types obscure the contract.
Branch design
- Handle invalid or exceptional cases early to reduce nesting.
- Extract a named predicate when a condition encodes domain logic.
- Use a lookup table or polymorphism when a large branch selects behavior by a stable key.
- Use
matchfor structural patterns, not as a compulsory replacement for every simple equality chain.
Expression boundaries
The expression reference
places comparisons above not, then and, then or in precedence. Parentheses
make a mixed condition easier to read. not always returns a Boolean, and a
chained comparison evaluates its middle expression only once.
assert not "" # empty string
assert bool("0") and bool("False") # both nonempty
assert (0 or 7) == 7
assert (0 and 7) == 0
assert (2 < 3 < 4) is True
value = 0
result = value if value is not None else 10
assert result == 0
Use x == "a" or x == "b", or x in {"a", "b"}; x == "a" or "b"
is always truthy because "b" is nonempty. A conditional expression
yes if condition else no evaluates only the selected result. value or default
would replace valid zero values as well as None. Independent if statements
can execute several bodies; an if/elif chain selects at most one. Its else
handles the case where no condition succeeds, and is optional.