🎯 Multiple Conditions
When your programs need to handle more than two possibilities, multiple conditions become essential. Python's elif statement allows you to check several conditions in sequence, creating sophisticated decision trees that can handle complex scenarios with many different outcomes.
Multiple conditions help you avoid deeply nested if statements and create cleaner, more readable code. Instead of checking conditions one inside another, you can list them in a clear, logical sequence.
# Multiple conditions with elif
grade = 85
if grade >= 90:
letter = "A"
print("Excellent work!")
elif grade >= 80:
letter = "B"
print("Good job!")
elif grade >= 70:
letter = "C"
print("You passed!")
elif grade >= 60:
letter = "D"
print("You need improvement.")
else:
letter = "F"
print("You failed.")
print(f"Your grade: {letter}")
🔄 The Elif Statement
The elif statement (short for "else if") allows you to check additional conditions after the initial if statement. Python evaluates elif conditions in order, executing the first one that's true and skipping the rest.
This sequential evaluation is important - once Python finds a true condition, it executes that block and skips all remaining elif and else clauses. This makes elif statements efficient and predictable.
# Elif statement evaluation order
time_of_day = 14 # 24-hour format
if time_of_day < 6:
greeting = "Good night"
elif time_of_day < 12:
greeting = "Good morning"
elif time_of_day < 18:
greeting = "Good afternoon"
else:
greeting = "Good evening"
print(f"{greeting}! It's {time_of_day}:00")
🧩 Complex Logical Conditions
You can combine multiple comparisons in a single condition using logical operators. This allows you to create sophisticated conditions that check several criteria simultaneously.
Complex conditions help you express nuanced decision logic without creating deeply nested if statements. Use parentheses to make complex conditions clear and readable.
# Complex logical conditions
age = 25
has_license = True
has_car = True
has_insurance = False
if age >= 18 and has_license and has_car and has_insurance:
print("You can drive legally!")
elif age >= 18 and has_license:
print("You can drive, but you need insurance and a car.")
elif age >= 18:
print("You're old enough, but you need a license.")
else:
print("You're too young to drive.")
# Complex condition with parentheses
temperature = 75
humidity = 45
if (temperature >= 70 and temperature <= 80) and (humidity >= 30 and humidity <= 50):
print("Perfect weather conditions!")
🔀 Quick Multiple Conditions Practice
Let's practice using elif statements to handle multiple different conditions!
Hands-on Exercise
Practice using if, elif, and else statements to handle multiple conditions.
# Multiple Conditions Practice - Grade calculator!
# Grade based on score
score = 85
# TODO: Your code here: Complete the grade calculator
# 90-100: "A grade"
# 80-89: "B grade"
# 70-79: "C grade"
# Below 70: "F grade"
if score >= 90:
print("A grade")
# Add elif and else statements here
Solution and Explanation 💡
Click to see the complete solution
# Multiple Conditions Practice - Simple solution
# Grade based on score
score = 85
# Complete grade calculator
if score >= 90:
print("A grade")
elif score >= 80: # 80-89
print("B grade")
elif score >= 70: # 70-79
print("C grade")
else: # Below 70
print("F grade")
Key Learning Points:
- 📌 elif statement: Checks additional conditions after if
- 📌 Order matters: Conditions are checked from top to bottom
- 📌 Mutually exclusive: Only one condition can execute
- 📌 else catches all: Handles any remaining cases
🔗 Chained Comparisons
Python allows you to chain comparison operators in a natural way, making range checks and multiple comparisons more readable. This feature is unique to Python and makes certain conditions much cleaner.
Chained comparisons are especially useful for checking if a value falls within a specific range or meets multiple criteria simultaneously.
# Chained comparisons
temperature = 72
humidity = 45
score = 85
# Range checking with chained comparisons
if 68 <= temperature <= 78:
print("Temperature is comfortable")
if 30 <= humidity <= 50:
print("Humidity is ideal")
# Multiple comparisons vs chained
age = 25
if 18 <= age <= 65: # Chained - more readable
print("Working age (chained)")
if age >= 18 and age <= 65: # Traditional - more verbose
print("Working age (traditional)")
# Grade checking with chained comparisons
if 90 <= score <= 100:
print("A grade")
elif 80 <= score < 90:
print("B grade")
elif 70 <= score < 80:
print("C grade")
else:
print("Below C grade")
⚡ Conditional Expressions (Ternary Operator)
Python provides a concise way to write simple if-else statements in a single line using conditional expressions. This is useful for simple assignments based on conditions.
# Conditional expressions (ternary operator)
age = 20
status = "adult" if age >= 18 else "minor"
print(f"Status: {status}")
# Comparing with regular if-else
score = 85
if score >= 70:
result = "pass"
else:
result = "fail"
# Same logic with ternary operator
result_ternary = "pass" if score >= 70 else "fail"
print(f"Result: {result_ternary}")
# Multiple ternary operators (avoid nesting)
weather = "sunny"
activity = "beach" if weather == "sunny" else "indoor games"
print(f"Today's activity: {activity}")
# Using ternary in function calls
numbers = [1, 2, 3, 4, 5]
print("Even" if len(numbers) % 2 == 0 else "Odd", "count of numbers")
🔀 Multiple Conditions vs Multiple If Statements
Understanding the difference between elif statements and multiple independent if statements is crucial for writing correct logic.
This distinction is crucial for logic operations and avoiding bugs in your conditional logic.
# Elif chain - only one executes
score = 85
print("=== ELIF CHAIN ===")
if score >= 90:
print("A grade")
elif score >= 80: # This executes, others are skipped
print("B grade")
elif score >= 70: # This is skipped
print("C grade")
# Multiple if statements - all true conditions execute
print("\n=== MULTIPLE IF STATEMENTS ===")
temperature = 75
if temperature > 70:
print("It's warm")
if temperature < 80:
print("It's not too hot")
if temperature >= 70:
print("Good weather for outdoor activities")
# All three conditions above are true, so all three messages print
📊 Common Multiple Condition Patterns
There are several patterns you'll encounter frequently when working with multiple conditions.
Pattern | Example | Use Case |
---|---|---|
Grade Classification | if score >= 90: ... elif score >= 80: | Categorizing ranges |
State Management | if state == "idle": ... elif state == "running": | Program states |
Input Validation | if len(input) == 0: ... elif not input.isalpha(): | Data validation |
Priority Checking | if urgent: ... elif important: ... else: | Priority systems |
Range Categories | if age < 13: ... elif age < 20: ... elif age < 65: | Age groups |
# Common multiple condition patterns
print("=== COMMON PATTERNS ===")
# User input validation
user_input = "hello123"
if len(user_input) == 0:
print("Input cannot be empty")
elif len(user_input) < 3:
print("Input too short")
elif not user_input.isalnum():
print("Input contains special characters")
else:
print("Valid input")
# Priority system
priority = "medium"
if priority == "critical":
print("Handle immediately!")
elif priority == "high":
print("Handle within 1 hour")
elif priority == "medium":
print("Handle within 4 hours")
else:
print("Handle when possible")
# Age group classification
age = 16
if age < 13:
category = "child"
elif age < 20:
category = "teenager"
elif age < 65:
category = "adult"
else:
category = "senior"
print(f"Age category: {category}")
📚 Key Takeaways
Test Your Knowledge
Test what you've learned about multiple conditions in Python:
🚀 What's Next?
Congratulations! You now understand the full spectrum of decision making in Python. You can handle simple conditions with if statements, binary choices with if-else, and complex scenarios with elif chains.
These conditional skills are essential for the next major topic: While Loops. Loops use conditions to determine when to repeat code, combining decision making with repetition.
Multiple conditions also work hand-in-hand with comparison operators, logical operations, and working with user input.
Understanding decision making prepares you for function development, error handling, and building interactive programs.
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.