Python — Making decisions with if and elif
In Python, an if and elif chain selects the first true condition. Indentation defines each branch, and an optional else handles all remaining cases.
A simple example
Follow one branch
- Start with n is 2
- Do this Is n positive?
- Result yes
n = 2
if n > 0:
print("yes")
else:
print("no")
yes
Classify a stock level
Indentation marks the statements that belong to each branch. elif is reached only after the zero condition fails. The final else covers the remaining nonnegative counts.
A student shop has three sketchbooks left. Empty stock gets a sold-out notice. A positive count of five or fewer gets a reorder notice, so three tells the shopkeeper to order soon.
Run the example
Python 3.8 or later. Run these commands from the directory containing the example.
python3 lesson.py
stock = 3
if stock == 0:
status = "sold out"
elif stock <= 5:
status = "order soon"
else:
status = "in stock"
print(status)
order soon
The stock count is 3. It passes the low-stock test after failing the zero test, so the program selects “order soon”. Zero belongs to both ranges and must be handled first.
Try it yourself
Try the boundary values 0, 5, and 6.
Check your answer
They produce “sold out”, “order soon”, and “in stock”, respectively. In a real inventory system, reject negative input before this classification.