Control Flow
Conditionals
Start with the value that the branches will test. A conditional is only useful when the branch condition is visible and meaningful.
Use if, elif, and else for one ordered choice. Python tests the branches from top to bottom and runs only the first matching block.
Source
temperature = 72
if temperature < 60:
print("cold")
elif temperature < 80:
print("comfortable")
else:
print("hot")Output
comfortableTruthiness is part of conditional flow. Empty collections are false, so if items: reads as “if there is anything to work with.”
Source
items = ["coat", "hat"]
if items:
print(f"packing {len(items)} items")Output
packing 2 itemsUse the ternary expression when you are choosing a value. If either side needs multiple statements, use a normal if block instead.
Source
status = "ok" if temperature < 90 else "danger"
print(status)Output
okNotes
- Python has no mandatory parentheses around conditions; the colon and indentation define the block.
- Comparison operators such as
<and==can be chained, as in0 < value < 10. - Keep branch bodies short; move larger work into functions so the decision remains easy to scan.
See also
- prerequisite: Booleans
- prerequisite: Truthiness
- related: Guard Clauses
- related: Match Statements
Run the complete example
Expected output
comfortable
packing 2 items
ok
Execution time appears here after you run the example.