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.