- Use else to handle when conditions are False
- Chain multiple conditions with elif
- Build complete decision trees
- Understand nested if statements
Mastering if, elif, and else
In the previous lesson, you learned how to make decisions with if statements. But life rarely offers just one option. When someone asks "Coffee or tea?", they expect one of two answers. When a traffic light changes, it goes through three colors. When you grade a test, there might be A, B, C, D, or F.
Python's else and elif keywords let you handle all these scenarios gracefully. Together with if, they form the complete decision-making toolkit that powers everything from simple yes/no choices to complex decision trees.
The else Statement: Handling the Alternative
The else statement catches everything that didn't match the if condition. Think of it as saying "if not that, then this."
Structure of if-else
if-else Structure
if condition: ← Check the condition
# do this ← Runs if condition is True
else: ← No condition needed!
# do that ← Runs if condition is False
One path ALWAYS executes - either if OR else, never both!
Real-World Analogy
Think of a light switch:
- if the switch is ON → light is on
- else (switch is OFF) → light is off
There's no third option. It's one or the other.
Basic if-else Example
age = 15
if age >= 18:
print("You are an adult.")
print("You can vote!")
else:
print("You are a minor.")
print("You cannot vote yet.")
print("Thanks for checking!") # Always runs
Output (since age is 15):
You are a minor.
You cannot vote yet.
Thanks for checking!
More if-else Examples
# Weather decision
temperature = 28
if temperature > 25:
print(" It's warm! Wear light clothes.")
else:
print(" It's cool. Bring a jacket.")
# Login check
password_correct = False
if password_correct:
print(" Welcome back!")
else:
print(" Incorrect password. Try again.")
# Even or odd
number = 7
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
The elif Statement: Multiple Choices
What if you have more than two options? That's where elif (short for "else if") comes in. It lets you check multiple conditions in sequence.
Structure of if-elif-else
if-elif-else Structure
if condition1: ← Check first
# do A
elif condition2: ← Check if first was False
# do B
elif condition3: ← Check if previous were False
# do C
else: ← If ALL above are False
# do D
Only ONE block executes - the first True condition wins!
Real-World Analogy
Think of a vending machine:
- if you press A1 → give chips
- elif you press A2 → give candy
- elif you press A3 → give soda
- else → display "Invalid selection"
Only one item comes out!
Grade Calculator Example
score = 85
if score >= 90:
grade = "A"
message = "Excellent!"
elif score >= 80:
grade = "B"
message = "Good job!"
elif score >= 70:
grade = "C"
message = "Not bad!"
elif score >= 60:
grade = "D"
message = "You passed."
else:
grade = "F"
message = "Need to improve."
print(f"Score: {score}")
print(f"Grade: {grade}")
print(f"Comment: {message}")
Output:
Score: 85
Grade: B
Comment: Good job!
Important: Even though 85 is also >= 70 and >= 60, only the first matching condition (>= 80) executes!
Day of the Week Example
day_number = 3
if day_number == 1:
day = "Monday"
elif day_number == 2:
day = "Tuesday"
elif day_number == 3:
day = "Wednesday"
elif day_number == 4:
day = "Thursday"
elif day_number == 5:
day = "Friday"
elif day_number == 6:
day = "Saturday"
elif day_number == 7:
day = "Sunday"
else:
day = "Invalid day number"
print(f"Day {day_number} is {day}")
Visual Decision Flow
Understanding how Python evaluates conditions is crucial:
How Python Processes if-elif-else
score = 75
if score >= 90: Is 75 >= 90? NO → Skip
print("A")
elif score >= 80: Is 75 >= 80? NO → Skip
print("B")
elif score >= 70: Is 75 >= 70? YES → RUN THIS!
print("C")
elif score >= 60: SKIPPED!
print("D") (already found match)
else: SKIPPED!
print("F") (already found match)
Output: C
Nested if Statements
Sometimes you need to make decisions within decisions. This is called nesting.
When to Use Nested ifs
Think of it like a phone tree:
- First, are you a new or existing customer?
- If existing, is your issue about billing or technical support?
- If billing, is it about payments or statements?
Nested if Example
is_member = True
purchase_amount = 150
print(" Discount Calculator")
print("=" * 30)
if is_member:
print(" Member status: Active")
if purchase_amount >= 100:
discount = 20
print(f" Large purchase discount: {discount}%")
elif purchase_amount >= 50:
discount = 10
print(f" Medium purchase discount: {discount}%")
else:
discount = 5
print(f" Member base discount: {discount}%")
else:
print(" Not a member")
if purchase_amount >= 100:
discount = 10
print(f" Large purchase discount: {discount}%")
else:
discount = 0
print("No discount available")
final_price = purchase_amount * (1 - discount/100)
print("=" * 30)
print(f"Original: ${purchase_amount}")
print(f"Discount: {discount}%")
print(f"Final: ${final_price:.2f}")
Visual Representation of Nesting
Nested Decision Tree
is_member?
True False
purchase>=100? purchase>=100?
20% other 10% 0%
Caution: Too much nesting makes code hard to read. If you have more than 3 levels, consider restructuring your logic.
The Order of Conditions Matters!
The sequence of your conditions can completely change the result:
Wrong Order (Common Mistake)
score = 95
# WRONG: More general condition first
if score >= 60:
print("D") # This runs! (95 >= 60)
elif score >= 70:
print("C") # Never reached
elif score >= 80:
print("B") # Never reached
elif score >= 90:
print("A") # Never reached
# Output: D (but should be A!)
Correct Order
score = 95
# CORRECT: Most specific conditions first
if score >= 90:
print("A") # This runs! (95 >= 90)
elif score >= 80:
print("B")
elif score >= 70:
print("C")
elif score >= 60:
print("D")
else:
print("F")
# Output: A
Practical Examples
Example 1: Age Group Classifier
age = 25
print(" Age Group Classifier")
print("-" * 30)
if age < 0:
group = "Invalid age"
elif age < 2:
group = "Infant"
elif age < 13:
group = "Child"
elif age < 20:
group = "Teenager"
elif age < 30:
group = "Young Adult"
elif age < 60:
group = "Adult"
else:
group = "Senior"
print(f"Age: {age}")
print(f"Group: {group}")
Example 2: Simple Calculator
num1 = 10
num2 = 5
operation = "+"
print(" Simple Calculator")
print("=" * 25)
if operation == "+":
result = num1 + num2
symbol = "+"
elif operation == "-":
result = num1 - num2
symbol = "-"
elif operation == "*":
result = num1 * num2
symbol = "×"
elif operation == "/":
if num2 != 0:
result = num1 / num2
symbol = "÷"
else:
result = "Error: Division by zero!"
symbol = "÷"
else:
result = "Unknown operation"
symbol = "?"
print(f"{num1} {symbol} {num2} = {result}")
Example 3: Shipping Cost Calculator
weight = 2.5 # kg
destination = "international"
print(" Shipping Calculator")
print("-" * 30)
if destination == "local":
if weight <= 1:
cost = 5.00
elif weight <= 5:
cost = 10.00
else:
cost = 15.00
elif destination == "national":
if weight <= 1:
cost = 10.00
elif weight <= 5:
cost = 20.00
else:
cost = 35.00
elif destination == "international":
if weight <= 1:
cost = 25.00
elif weight <= 5:
cost = 50.00
else:
cost = 100.00
else:
cost = 0
print("Invalid destination!")
print(f"Weight: {weight} kg")
print(f"Destination: {destination}")
print(f"Shipping Cost: ${cost:.2f}")
Key Takeaways
Remember These Points
else: runs when if (and all elif) conditions are False
elif: short for "else if" - checks another condition
Only ONE block runs in an if-elif-else chain
Order matters! Put specific conditions before general ones
else is optional - use it when you need a default action
You can have unlimited elif statements
Nested ifs are possible but don't over-nest (max 3 levels)
What's Next?
Excellent! You've mastered the art of decision-making in Python. But what about repetitive tasks? Imagine printing numbers 1 to 100, or processing every item in a shopping cart. In the next lesson, we'll learn about for loops – Python's way of doing things repeatedly without writing the same code over and over!
