age >= 13 and age <= 19 is True only for teenagers.
True / Falseif / elif / else — pick exactly one branchand, or, not
Pass or fail. Leap year or not. Adult or minor. The computer can't judge — but it can compare, and it can branch. Today we turn a single if into a real decision tree.
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B") # <- this one wins
else:
print("keep going")
True / FalseEvery condition is really a yes/no question. These six operators are how you ask them.
7 > 3 # True greater than
3 >= 3 # True greater or equal
2 < 9 # True less than
5 == 5 # True EQUAL (two ='s!)
5 != 6 # True not equal
4 <= 2 # False less or equal
= assigns a value.
== asks "are these equal?". Mixing them up is the #1 beginner bug.
elif — pick exactly one branch
Python checks branches top to bottom. The first one that is True runs — the rest are skipped entirely.
def classify(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
else:
return "F"
>= 70 before >= 90 and every score becomes a "C".
and · or · notBoth sides must be true.
At least one side must be true.
Flips true and false.
age >= 13 and age <= 19 is True only for teenagers.
An if can live inside another if. Often you can flatten it with and — but nesting is fine when the inner question only makes sense after the outer one.
if logged_in:
if is_admin:
print("Welcome, boss")
else:
print("Welcome, user")
else:
print("Please log in")
# Same idea, flattened with 'and'
if logged_in and is_admin:
print("Welcome, boss")
elif logged_in:
print("Welcome, user")
else:
print("Please log in")
Divisible by 4, and (not divisible by 100 or divisible by 400). All three operators at once.
def is_leap_year(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
print(is_leap_year(2000)) # True (÷400)
print(is_leap_year(1900)) # False (÷100 but not ÷400)
print(is_leap_year(2024)) # True
if/else needed — a comparison already is True or False. Just return it.
= instead of == inside an if — Python raises a SyntaxError.>= 70 before >= 90, so an A becomes a C.if x == 1 or 2 — you mean x == 1 or x == 2.ifs when you meant elif — several branches all fire.: at the end of the line, or mis-indenting the body.
classify_grade(score) returns A / B / C / D / F using a chained if / elif / else.
is_leap_year(year) returns True / False — a showcase for and / or / not.
students/<your-username>/D06_grade_classifier.py. Full brief in lab/module_1_foundations/D06_grade_classifier/problem.md. PR before 12:00.
if / elif / else.
and, or, and not.
for loops + range() on Day 7.