Control Flow and Logic
20 min read
Elif Chains
Elif Chains
Sometimes a program needs more than two choices.
For example:
- If score is 80 or more, grade is A
- If score is 60 or more, grade is B
- Otherwise, grade is C
Python uses elif when you want to check more than one condition.
What Is Elif?
elif means else if.
It lets Python check another condition if the first if condition is false.
score = 75
if score >= 80:
print("Grade A")
elif score >= 60:
print("Grade B")
else:
print("Grade C")
How It Works
Python checks from top to bottom:
- First, it checks
score >= 80 - If false, it checks
score >= 60 - If true, it prints
Grade B - If all conditions are false,
elseruns
Why Order Matters
Python stops when it finds the first true condition.
So always place higher conditions first.
score = 90
if score >= 80:
print("A")
elif score >= 60:
print("B")
else:
print("C")
Another Example
age = 15
if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")
Code Along
marks = 45
if marks >= 70:
print("Excellent")
elif marks >= 50:
print("Pass")
else:
print("Fail")
Mini Challenge
Build a grading system.
Steps:
- Ask the user to enter a score
- If the score is 80 or more, print:
Grade A - If the score is 60 or more, print:
Grade B - Otherwise, print:
Grade C
Real World Use Case
Schools, websites, and apps use elif to show different results based on scores, ages, plans, or user choices.
Quiz
- What does
elifmean? - When does Python check an
elifblock? - Why does order matter in
elifchains? - What happens if all conditions are false?
Assignment
Create a program that asks the user for age:
- If age is 18 or more, print
Adult - If age is 13 or more, print
Teenager - Otherwise, print
Child
Summary
You learned how to use elif to handle multiple choices and make smarter Python programs.