Learning LibraryCore Coding LibraryTeens

If / elif / else in Python: turn a policy into code

Every business runs on rules. Who ships free? Which discount applies? if, elif, and else are how a sentence in a policy becomes a decision in code.

The big idea

An if runs its indented block only when its condition is true; elif adds further cases and else catches everything left.

See it in code

1The basics

if/else picks exactly one of two paths. The indented lines under each belong to that path:

python
order_total = 90
free_shipping_min = 75
flat_shipping = 6

if order_total >= free_shipping_min:
    shipping = 0
else:
    shipping = flat_shipping
print("Shipping:", shipping)
Run it. Does a $90 order ship free?
Shipping: 0

The condition was true, so shipping became 0 and the else block was skipped entirely. The final print isn't indented, so it runs either way.

2A step further

elif adds a middle tier. Python tests the conditions from the top and runs only the first one that's true:

python
order_total = 60
free_shipping_min = 75
reduced_min = 40
flat_shipping = 6
reduced_shipping = 3

if order_total >= free_shipping_min:
    shipping = 0
elif order_total >= reduced_min:
    shipping = reduced_shipping
else:
    shipping = flat_shipping
print("Shipping:", shipping)
Run it. Three tiers, one $60 order:
Shipping: 3

60 isn't at least 75, so the first test failed. It is at least 40, so the elif ran, and Python never evaluated the else.

3At Evergreen

Rules combine. This checkout applies a recycling credit to customers who sent back a worn-out item, then computes the total:

python
order_total = 70
free_shipping_min = 75
flat_shipping = 6
returned_item = True
recycle_credit = 5

if order_total >= free_shipping_min:
    shipping = 0
else:
    shipping = flat_shipping

credit = 0
if returned_item:
    credit = recycle_credit

total = order_total + shipping - credit
print(f"Total: ${total:.2f}")
Run it. Shipping, a credit, and a total:
Total: $71.00

Notice where total is computed: after the credit is decided. Move that line above the second if and the customer is overcharged by $5, because a calculation uses values as they are at that moment.

The same idea, everywhere

The same structure classifies anything. A codon is a start, a stop, or neither. A trading signal is buy, sell, or hold. A form field is valid or it isn't.

Try it yourself

Set order_total = 75 and confirm shipping is free. Then add a bundle discount: if items >= 3, take 10% off order_total before anything else is calculated.

The common mistake

Ordering branches from loosest to tightest. If order_total >= reduced_min came first, a $90 order would match it and pay $3, never reaching the free-shipping test. Put the most specific condition first.

What it unlocks

Conditions are built from comparison operators and combined with and, or, not. Inside a for loop, an if acts on some passes and not others.

Want the simpler version? Read the Kids version →