Run a block of code only when a condition is true, and choose between branches.
# simple if
x = 10
if x > 5:
print("x is greater than 5")
# ans: output: x is greater than 5
x =The indented line runs only when the condition is True.
# if with else
age = 18
if age >= 18:
print("Adult")
else:
print("Minor")
# ans: output: Adult
age =Exactly one of the two branches runs.
# multiple conditions
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("F")
# ans: output: B
score =Conditions are checked top to bottom; the first True one wins and the rest are skipped.
# if inside if
x = 15
if x > 10:
if x < 20:
print("Between 10 and 20")
# ans: output: Between 10 and 20
x =The inner if is only checked when the outer one is True.
# many elif branches
num = 3
if num == 1:
print("One")
elif num == 2:
print("Two")
elif num == 3:
print("Three")
# ans: output: Three
num =With no else, it is possible that nothing runs at all.
Predict the output, then press → to trace the code and check.
# what is printed?
x = 5
if x > 10:
print("Big")
else:
print("Small")
# ans: Small
# what about this?
score = 90
if score >= 90:
print("A")
elif score >= 80:
print("B")
# ans: A (only the first matching condition runs)
# edge case?
x = 0
if x:
print("True")
else:
print("False")
# ans: False (0 is falsy)
# what prints?
age = 18
if age >= 18:
print("Adult")
if age < 21:
print("Not 21 yet")
# ans: Adult
# ans: Not 21 yet (two separate ifs: both run)
# tricky: what happens?
if True:
x = 5
else:
x = 10
y = 20
# ans: x is 5, y is 20 (y = 20 is outside the if)
# what is result?
x = 15
if x > 10:
if x < 20:
result = "Between"
else:
result = "Big"
# ans: result is "Between"
# what prints?
score = 70
if score >= 70:
pass
else:
print("Fail")
# ans: nothing (pass does nothing)
# condition evaluation?
x = None
if x:
print("Yes")
else:
print("No")
# ans: No (None is falsy)
# multiple conditions?
x = 5
if x > 0 and x < 10:
print("In range")
# ans: In range
# what happens?
if False:
print("A")
elif True:
print("B")
elif True:
print("C")
# ans: B (stops at the first True)
# empty list check?
items = []
if items:
print("Has items")
else:
print("Empty")
# ans: Empty (an empty list is falsy)
Only the indented lines belong to the if; the next unindented line always runs.
In an if / elif chain, Python stops at the first True condition and skips the rest.
Two if statements in a row are both checked.
0, None and an empty list [] all count as False.
passDoes nothing: a placeholder for a block that must exist.