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
print(5 > 3)
print(5 == 5)
print(5 != 4)
print(5 <= 2)Output
True True True False
How it works
- Comparisons give a boolean (
TrueorFalse). >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 = 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
ifis checked first. - If it is
True, the indented lines underifrun. - If it is
False, the indented lines underelserun instead. - The indentation — the spaces at the start of a line — tells Python which lines belong to each branch.
Adding more choices with elif
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
elifmeans 'else, if...' — it checks another condition only when the ones above wereFalse.- Python tests each condition from top to bottom and stops at the first
Trueone. elseat the end catches everything that did not match.
Combining conditions
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
andisTrueonly when both conditions are true.orisTruewhen at least one condition is true.- You can write
memberinstead ofmember == True, sincememberis already a boolean.
The pattern
if checks a condition; elif adds more conditions; else is the fallback when nothing matched.What you have learned
- Comparisons (
>,<,>=,<=,==,!=) give a boolean. ifruns code when its condition isTrue.elifadds extra conditions, checked in order.elseruns when nothing above matched.- Combine conditions with
and/or. - Indentation decides which lines belong to each branch.