Lesson contents

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

  1. Start with n is 2
  2. Do this Is n positive?
  3. Result yes
The condition selects the first branch. Changing the value to zero selects the other branch.
lesson.py
n = 2
if n > 0:
    print("yes")
else:
    print("no")
Output
yes
Advertisements

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.

On the shelf: 3 books. Low-stock limit: 5 books. Shelf notice: Order soon.
Decide when to restock

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
lesson.py
stock = 3
if stock == 0:
    status = "sold out"
elif stock <= 5:
    status = "order soon"
else:
    status = "in stock"
print(status)
Output
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.

The Python Tutorial

Related tags

  • Python
  • conditions
  • branching
  • comparison