Our learning goals are understanding the syntax and execution order of elif (else if), learning to handle multiple conditions, such as grading, temperature classification, or age categories and mastering the top-down flow—the program checks conditions in sequence and stops once one is true.
Previously, we only had two choices: if and else. But in real life, we often have more possibilities, for example, grades A, B, C, D. This is where we use elif, which means “else if”. It allows us to add more branches. The program checks conditions from top to bottom, runs the first true one, and skips the rest.
Basic Syntax:
if condition1:
code_1
elif condition2:
code_2
elif condition3:
code_3
else:
code_4
Conditions are checked from top to bottom. Only the first True condition runs; if none are true, the else block runs.
Example A: Grading System
score = int(input("Enter your score: "))
if score >= 90:
print("Grade A")
elif score >= 75:
print("Grade B")
elif score >= 60:
print("Grade C")
else:
print("Grade D")
The program first checks >=90; if false, it continues to the next. If the conditions are written in reverse order (for example, >=60 first), even a high score will be judged as a C because the first condition is true.
Example B: Temperature Classification
t = float(input("Enter today's temperature (°C): "))
if t >= 35:
print("Very Hot")
elif t >= 25:
print("Warm")
elif t >= 15:
print("Cool")
else:
print("Cold")
This is a typical “range test” example, we should ensure the ranges don’t overlap.
Common Mistakes:
>=60 twice) can cause misclassification.elif must align with if and else).: at the end of condition lines.else, leaving some cases uncovered.Hands-on practice:
Exercise A: Input two numbers and an operator (+, -, *, /) and calculate the result.
Answer example A:
a = float(input("a = "))
b = float(input("b = "))
op = input("Operator (+, -, *, /): ")
if op == "+":
print("Result =", a + b)
elif op == "-":
print("Result =", a - b)
elif op == "*":
print("Result =", a * b)
elif op == "/":
if b == 0:
print("Cannot divide by zero!")
else:
print("Result =", round(a / b, 2))
else:
print("Invalid operator!")
The above nested if for division-by-zero is an advanced use of multi-branch logic.
With elif, we can now write more complex decision-making logic.