TutreNews Learn

Decisions and loops

if, elif, else

Goal: Branch with conditions and boolean logic · 9 min

if runs a block only when its condition is True. The block is defined by indentation (4 spaces by convention) after a colon.

if temp > 25:
    print("hot")
elif temp > 15:
    print("mild")
else:
    print("cold")

Python checks the conditions top to bottom and runs only the first matching block. Comparisons: == != < > <= >= (note == compares, = assigns). Combine with and, or, not.

Worked example: Ticket price

  1. age = 15 → not < 6.
  2. 15 < 18 is True → price 5.
  3. The else branch is skipped.
age = 15
if age < 6:
    price = 0
elif age < 18:
    price = 5
else:
    price = 9
print(price)

Output:

5