Control Flow

Conditionals

if, elif, and else choose which block runs.

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

comfortable
value?case Acase B
A predicate sorts a value into one of several branches; if/elif/else is the explicit spelling.

Truthiness 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 items

Use 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

ok

Notes

See also

Run the complete example

Example code

Expected output

comfortable
packing 2 items
ok

Execution time appears here after you run the example.