05-selection-if-elif-else.py
python-for-j277 / control-flow  ·  Lesson 05
Lesson 05 — Control flow

Selection: if / elif / else

Make your program choose what to do.

Selection lets a program make decisions. It runs some code only when a condition is true.

Comparing values

compare.py
print(5 > 3)
print(5 == 5)
print(5 != 4)
print(5 <= 2)
Output
True
True
True
False
How it works
  • Comparisons give a boolean (True or False).
  • > greater than, < less than, >= at least, <= at most.
  • == checks if two values are equal (two equals signs).
  • != checks if they are not equal.
= is not === stores a value; == checks if two values are equal. Mixing them up is the most common beginner mistake.

if and else

age.py
age = int(input("Enter your age: "))
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")
Output
Enter your age: 16
You are a minor.
How it works
  • The condition after if is checked first.
  • If it is True, the indented lines under if run.
  • If it is False, the indented lines under else run instead.
  • The indentation — the spaces at the start of a line — tells Python which lines belong to each branch.

Adding more choices with elif

grade.py
score = int(input("Enter score: "))
if score >= 70:
    print("Grade: Distinction")
elif score >= 50:
    print("Grade: Merit")
elif score >= 40:
    print("Grade: Pass")
else:
    print("Grade: Fail")
Output
Enter score: 55
Grade: Merit
How it works
  • elif means 'else, if...' — it checks another condition only when the ones above were False.
  • Python tests each condition from top to bottom and stops at the first True one.
  • else at the end catches everything that did not match.

Combining conditions

logic.py
age = 15
member = True
if age >= 12 and member == True:
    print("Entry allowed")
if age < 12 or member == False:
    print("Please see staff")
Output
Entry allowed
How it works
  • and is True only when both conditions are true.
  • or is True when at least one condition is true.
  • You can write member instead of member == True, since member is already a boolean.
The patternif checks a condition; elif adds more conditions; else is the fallback when nothing matched.

What you have learned

  • Comparisons (>, <, >=, <=, ==, !=) give a boolean.
  • if runs code when its condition is True.
  • elif adds extra conditions, checked in order.
  • else runs when nothing above matched.
  • Combine conditions with and / or.
  • Indentation decides which lines belong to each branch.