Prerequisites
- Basic understanding of programming concepts ๐
- Python installation (3.8+) ๐
- VS Code or preferred IDE ๐ป
What you'll learn
- Understand the concept fundamentals ๐ฏ
- Apply the concept in real projects ๐๏ธ
- Debug common issues ๐
- Write clean, Pythonic code โจ
๐ฏ Introduction
Welcome to this exciting tutorial on if-elif-else statements in Python! ๐ Have you ever wondered how programs make complex decisions? Like how a video game determines your characterโs level, or how an app decides which discount to apply? Thatโs the magic of multiple conditions!
In this guide, weโll explore how to create smart Python programs that can evaluate multiple scenarios and make the right choice every time. Whether youโre building a grading system ๐, a game ๐ฎ, or an e-commerce app ๐, mastering if-elif-else statements is essential for writing intelligent code.
By the end of this tutorial, youโll be confidently writing decision trees that handle any situation! Letโs dive in! ๐โโ๏ธ
๐ Understanding If-Elif-Else
๐ค What is If-Elif-Else?
If-elif-else is like a smart traffic controller ๐ฆ at a busy intersection. It looks at the current situation and decides which path to take:
- If the light is green โ Go! ๐ข
- Elif (else if) the light is yellow โ Slow down! ๐ก
- Else โ Stop! ๐ด
In Python terms, if-elif-else allows your program to:
- โจ Check multiple conditions in order
- ๐ Execute different code blocks based on which condition is true
- ๐ก๏ธ Provide a default action when no conditions match
๐ก Why Use If-Elif-Else?
Hereโs why developers love if-elif-else:
- Clear Decision Making ๐ฏ: Handle complex logic elegantly
- Readable Code ๐: Easy to understand the flow
- Efficient Execution โก: Stops checking once a condition is met
- Complete Coverage ๐ก๏ธ: Handle all possible scenarios
Real-world example: Imagine a smart home system ๐ . It needs to adjust temperature based on time and weather - thatโs where if-elif-else shines!
๐ง Basic Syntax and Usage
๐ Simple Example
Letโs start with a friendly example:
# ๐ Hello, if-elif-else!
age = 18
if age < 13:
print("You're a child! ๐ถ Enjoy your youth!")
elif age < 20:
print("You're a teenager! ๐ These are exciting times!")
elif age < 60:
print("You're an adult! ๐ผ Time to conquer the world!")
else:
print("You're a senior! ๐ Share your wisdom!")
# Output: You're a teenager! ๐ These are exciting times!
๐ก Explanation: Python checks each condition from top to bottom. Once it finds a true condition, it executes that block and skips the rest!
๐ฏ Common Patterns
Here are patterns youโll use daily:
# ๐๏ธ Pattern 1: Grade Calculator
score = 85
if score >= 90:
grade = "A ๐"
elif score >= 80:
grade = "B ๐"
elif score >= 70:
grade = "C โ
"
elif score >= 60:
grade = "D ๐"
else:
grade = "F ๐ข"
print(f"Your grade: {grade}")
# ๐จ Pattern 2: Multiple Conditions with and/or
temperature = 25
humidity = 70
if temperature > 30 and humidity > 80:
weather = "Hot and humid! ๐ฅต๐ฆ"
elif temperature > 30 or humidity > 80:
weather = "Uncomfortable weather ๐"
elif temperature < 10:
weather = "Cold! Bundle up! ๐งฅ"
else:
weather = "Pleasant weather! ๐"
# ๐ Pattern 3: Nested Conditions
day = "Saturday"
hour = 14
if day in ["Saturday", "Sunday"]:
if hour < 12:
activity = "Weekend brunch! ๐ฅ"
elif hour < 18:
activity = "Weekend fun time! ๐ฎ"
else:
activity = "Weekend movie night! ๐ฟ"
else:
if hour < 9:
activity = "Morning commute โ"
elif hour < 17:
activity = "Work time ๐ป"
else:
activity = "Evening relaxation ๐๏ธ"
๐ก Practical Examples
๐ Example 1: Shopping Cart Discount System
Letโs build something real:
# ๐๏ธ Smart discount calculator
def calculate_discount(total_amount, is_member, items_count):
discount_percent = 0
discount_message = ""
# ๐ฏ Check multiple conditions for best discount
if total_amount >= 1000 and is_member:
discount_percent = 20
discount_message = "๐ VIP Member Mega Discount!"
elif total_amount >= 500 and is_member:
discount_percent = 15
discount_message = "โญ Member Special Discount!"
elif total_amount >= 1000:
discount_percent = 10
discount_message = "๐ฐ Big Spender Discount!"
elif items_count >= 10:
discount_percent = 8
discount_message = "๐ฆ Bulk Purchase Discount!"
elif is_member:
discount_percent = 5
discount_message = "๐ค Member Discount!"
elif total_amount >= 100:
discount_percent = 3
discount_message = "โจ Thank You Discount!"
else:
discount_percent = 0
discount_message = "๐ณ Standard Price"
discount_amount = total_amount * (discount_percent / 100)
final_price = total_amount - discount_amount
print(f"\n๐ Order Summary:")
print(f"Original Total: ${total_amount:.2f}")
print(f"Discount: {discount_message} ({discount_percent}%)")
print(f"You Save: ${discount_amount:.2f}")
print(f"Final Price: ${final_price:.2f} ๐")
return final_price
# ๐ฎ Let's test it!
calculate_discount(1200, True, 5) # VIP member with high purchase
calculate_discount(600, True, 3) # Regular member
calculate_discount(50, False, 2) # Small purchase
๐ฏ Try it yourself: Add a special holiday discount condition!
๐ฎ Example 2: Game Character Level System
Letโs make it fun:
# ๐ RPG character progression system
def check_character_status(level, experience, achievements):
title = ""
perks = []
next_goal = ""
# ๐ฏ Determine character title and perks
if level >= 50 and len(achievements) >= 20:
title = "๐ Legendary Hero"
perks = ["โก Lightning Speed", "๐ก๏ธ Divine Shield", "๐ฅ Dragon's Breath"]
next_goal = "You've reached the pinnacle!"
elif level >= 40:
title = "โ๏ธ Master Warrior"
perks = ["๐ช Super Strength", "๐ Enhanced Speed"]
next_goal = "Collect 20 achievements for Legendary status!"
elif level >= 30 and experience >= 10000:
title = "๐ก๏ธ Elite Fighter"
perks = ["๐ฏ Perfect Aim", "๐ก๏ธ Iron Defense"]
next_goal = "Reach level 40 to become a Master!"
elif level >= 20:
title = "๐น Skilled Adventurer"
perks = ["๐ช Double Jump", "๐ฐ Extra Loot"]
next_goal = "Gain 10,000 XP and reach level 30!"
elif level >= 10:
title = "๐ก๏ธ Brave Warrior"
perks = ["โค๏ธ Extra Health"]
next_goal = "Level up to 20 for new abilities!"
else:
title = "๐ฑ Novice Explorer"
perks = ["๐ Starter Pack"]
next_goal = "Reach level 10 to unlock your first perk!"
# ๐ Display character info
print(f"\n๐ฎ CHARACTER STATUS")
print(f"{'='*30}")
print(f"Level: {level} | XP: {experience}")
print(f"Title: {title}")
print(f"Achievements: {len(achievements)} ๐")
print(f"\nโจ Active Perks:")
for perk in perks:
print(f" {perk}")
print(f"\n๐ฏ Next Goal: {next_goal}")
# ๐ Special messages
if level % 10 == 0 and level > 0:
print(f"\n๐ MILESTONE REACHED! Level {level} unlocked!")
# ๐ฎ Test our game system!
check_character_status(15, 3500, ["First Kill", "Speed Run", "Treasure Hunter"])
check_character_status(42, 15000, ["Dragon Slayer", "Speed Master"] + ["Badge"] * 18)
๐ Advanced Concepts
๐งโโ๏ธ Advanced Topic 1: Complex Condition Chaining
When youโre ready to level up, try this advanced pattern:
# ๐ฏ Advanced validation system
def validate_user_registration(username, password, email, age):
errors = []
warnings = []
status = "pending"
# ๐ Complex validation chain
if not username:
errors.append("โ Username is required")
elif len(username) < 3:
errors.append("โ Username too short (min 3 chars)")
elif not username.isalnum():
errors.append("โ Username must be alphanumeric")
if not password:
errors.append("โ Password is required")
elif len(password) < 8:
errors.append("โ Password too weak (min 8 chars)")
elif password == username:
errors.append("โ Password cannot be same as username")
elif password.lower() == "password":
warnings.append("โ ๏ธ Please choose a stronger password")
if "@" not in email or "." not in email:
errors.append("โ Invalid email format")
elif email.count("@") > 1:
errors.append("โ Email contains multiple @ symbols")
if age < 13:
errors.append("โ Must be 13 or older")
elif age < 18:
warnings.append("โ ๏ธ Parental consent required")
elif age > 120:
warnings.append("โ ๏ธ Please verify your age")
# ๐ฏ Determine final status
if errors:
status = "rejected ๐ซ"
print("\nโ Registration Failed!")
for error in errors:
print(f" {error}")
elif warnings:
status = "approved with warnings โ ๏ธ"
print("\nโ
Registration Successful (with warnings):")
for warning in warnings:
print(f" {warning}")
else:
status = "approved โ
"
print("\n๐ Perfect Registration! Welcome aboard!")
return status
# ๐ช Test the validation
validate_user_registration("jo", "12345", "invalid-email", 12)
validate_user_registration("alice123", "securepass123", "[email protected]", 16)
๐๏ธ Advanced Topic 2: Dynamic Condition Building
For the brave developers:
# ๐ Dynamic pricing engine
def calculate_dynamic_price(base_price, **factors):
final_price = base_price
applied_modifiers = []
# ๐
Time-based pricing
hour = factors.get('hour', 12)
if 6 <= hour < 9:
final_price *= 1.2
applied_modifiers.append("๐
Morning Rush (+20%)")
elif 17 <= hour < 20:
final_price *= 1.3
applied_modifiers.append("๐ Evening Peak (+30%)")
elif 0 <= hour < 6:
final_price *= 0.7
applied_modifiers.append("๐ Night Owl Discount (-30%)")
# ๐ Location-based pricing
location = factors.get('location', 'standard')
if location == 'airport':
final_price *= 1.5
applied_modifiers.append("โ๏ธ Airport Premium (+50%)")
elif location == 'downtown':
final_price *= 1.2
applied_modifiers.append("๐๏ธ Downtown Rate (+20%)")
elif location == 'suburban':
final_price *= 0.9
applied_modifiers.append("๐๏ธ Suburban Discount (-10%)")
# ๐ฏ Loyalty pricing
trips_count = factors.get('trips_count', 0)
if trips_count >= 100:
final_price *= 0.7
applied_modifiers.append("๐ Platinum Member (-30%)")
elif trips_count >= 50:
final_price *= 0.8
applied_modifiers.append("๐ฅ Gold Member (-20%)")
elif trips_count >= 20:
final_price *= 0.9
applied_modifiers.append("๐ฅ Silver Member (-10%)")
# ๐ Display pricing breakdown
print(f"\n๐ฐ PRICING CALCULATION")
print(f"{'='*30}")
print(f"Base Price: ${base_price:.2f}")
print(f"\n๐ Applied Modifiers:")
for modifier in applied_modifiers:
print(f" {modifier}")
print(f"\n๐ณ Final Price: ${final_price:.2f}")
return final_price
# ๐ฏ Test dynamic pricing
calculate_dynamic_price(10, hour=18, location='airport', trips_count=75)
โ ๏ธ Common Pitfalls and Solutions
๐ฑ Pitfall 1: Order Matters!
# โ Wrong way - incorrect order!
age = 25
if age >= 18:
print("Adult") # This executes for everyone 18+
elif age >= 65:
print("Senior") # This NEVER executes! ๐ฐ
elif age >= 13:
print("Teen") # This NEVER executes for 18+!
# โ
Correct way - most specific first!
age = 25
if age >= 65:
print("Senior ๐")
elif age >= 18:
print("Adult ๐ผ") # Now this works correctly!
elif age >= 13:
print("Teen ๐")
else:
print("Child ๐ถ")
๐คฏ Pitfall 2: Forgetting else
# โ Dangerous - no default case!
payment_method = "bitcoin"
if payment_method == "credit_card":
process_credit_payment()
elif payment_method == "paypal":
process_paypal_payment()
# ๐ฅ What happens with bitcoin? Nothing!
# โ
Safe - always have a fallback!
payment_method = "bitcoin"
if payment_method == "credit_card":
print("๐ณ Processing credit card...")
elif payment_method == "paypal":
print("๐
ฟ๏ธ Processing PayPal...")
else:
print("โ Payment method not supported!")
print("โน๏ธ Please use credit card or PayPal")
๐ค Pitfall 3: Using elif when if would work
# โ Inefficient - only one can be true anyway
score = 85
if score > 90:
print("Grade: A")
elif score > 80 and score <= 90: # Redundant condition!
print("Grade: B")
elif score > 70 and score <= 80: # Redundant condition!
print("Grade: C")
# โ
Clean - elif already ensures previous conditions were false
score = 85
if score > 90:
print("Grade: A ๐")
elif score > 80: # We know it's <= 90 here!
print("Grade: B ๐")
elif score > 70: # We know it's <= 80 here!
print("Grade: C โ
")
๐ ๏ธ Best Practices
- ๐ฏ Order Conditions Properly: Most specific conditions first!
- ๐ Keep It Readable: Donโt nest too deeply (max 3 levels)
- ๐ก๏ธ Always Include else: Handle unexpected cases
- ๐จ Use Clear Conditions: Make logic obvious
- โจ Consider Refactoring: Too many elifs? Maybe use a dictionary!
# โจ When you have many conditions, consider this pattern:
def get_day_type(day):
# Instead of many if-elif statements...
day_types = {
"Monday": "Start of work week ๐ผ",
"Tuesday": "Getting into rhythm ๐ต",
"Wednesday": "Hump day! ๐ช",
"Thursday": "Almost there! ๐ฏ",
"Friday": "TGIF! ๐",
"Saturday": "Weekend vibes ๐",
"Sunday": "Rest day ๐ด"
}
return day_types.get(day, "Invalid day ๐ค")
๐งช Hands-On Exercise
๐ฏ Challenge: Build a Movie Ticket Pricing System
Create a smart ticket pricing system:
๐ Requirements:
- โ Different prices for age groups (child, adult, senior)
- ๐ท๏ธ Day of week affects pricing (weekday vs weekend)
- ๐ฅ Group discounts for 5+ people
- ๐ Special pricing for matinee shows (before 5 PM)
- ๐จ Each ticket type needs a description!
๐ Bonus Points:
- Add member card discounts
- Implement special holiday pricing
- Create a receipt formatter
๐ก Solution
๐ Click to see solution
# ๐ฏ Movie ticket pricing system!
def calculate_ticket_price(age, day_type, show_time, group_size, is_member=False):
# Base prices
base_price = 0
ticket_type = ""
discounts = []
# ๐ Age-based pricing
if age < 12:
base_price = 8
ticket_type = "๐ง Child Ticket"
elif age >= 65:
base_price = 10
ticket_type = "๐ด Senior Ticket"
else:
base_price = 15
ticket_type = "๐ซ Adult Ticket"
# Start with base price
final_price = base_price
# ๐
Day of week modifier
if day_type in ["Saturday", "Sunday"]:
final_price *= 1.25
discounts.append("๐
Weekend Premium (+25%)")
else:
discounts.append("๐ผ Weekday Price")
# โฐ Matinee discount
if show_time < 17:
final_price *= 0.8
discounts.append("๐
Matinee Discount (-20%)")
# ๐ฅ Group discount
if group_size >= 10:
final_price *= 0.7
discounts.append("๐ Large Group (-30%)")
elif group_size >= 5:
final_price *= 0.85
discounts.append("๐จโ๐ฉโ๐งโ๐ฆ Group Discount (-15%)")
# ๐ณ Member discount
if is_member:
final_price *= 0.9
discounts.append("โญ Member Discount (-10%)")
# ๐ Special promotions
if day_type == "Tuesday":
final_price *= 0.5
discounts.append("๐ Terrific Tuesday (-50%)")
# ๐ Generate receipt
print(f"\n๐ฌ MOVIE TICKET RECEIPT")
print(f"{'='*35}")
print(f"Ticket Type: {ticket_type}")
print(f"Base Price: ${base_price:.2f}")
print(f"\n๐ Applied Discounts/Charges:")
for discount in discounts:
print(f" {discount}")
print(f"\n๐ฐ Final Price: ${final_price:.2f}")
print(f"{'='*35}")
# ๐ฏ Add recommendations
if not is_member and final_price > 10:
print("\n๐ก Tip: Become a member to save 10% on all tickets!")
if group_size == 4:
print("\n๐ก Tip: One more person and you get group discount!")
return final_price
# ๐ฎ Test the system!
print("๐ฟ Welcome to Python Cinema! ๐ฟ\n")
# Different scenarios
calculate_ticket_price(8, "Saturday", 14, 1) # Child matinee on weekend
calculate_ticket_price(35, "Tuesday", 19, 6, True) # Adult group on Tuesday
calculate_ticket_price(70, "Monday", 15, 2) # Senior couple on weekday
# ๐ฏ Advanced: Calculate total for a family
family = [
{"age": 40, "member": True},
{"age": 38, "member": True},
{"age": 10, "member": False},
{"age": 8, "member": False}
]
total = 0
print("\n๐จโ๐ฉโ๐งโ๐ฆ FAMILY PACKAGE:")
for i, person in enumerate(family, 1):
print(f"\nPerson {i}:")
price = calculate_ticket_price(
person["age"],
"Saturday",
20,
len(family),
person["member"]
)
total += price
print(f"\n๐ FAMILY TOTAL: ${total:.2f}")
๐ Key Takeaways
Youโve learned so much! Hereโs what you can now do:
- โ Create complex decision trees with if-elif-else ๐ช
- โ Handle multiple conditions elegantly ๐ฏ
- โ Avoid common mistakes like incorrect ordering ๐ก๏ธ
- โ Write readable conditional logic that others understand ๐
- โ Build real-world applications with smart decision making! ๐
Remember: Good conditional logic is like a well-designed flowchart - clear, logical, and handles all cases! ๐ค
๐ค Next Steps
Congratulations! ๐ Youโve mastered if-elif-else statements!
Hereโs what to do next:
- ๐ป Practice with the movie ticket exercise above
- ๐๏ธ Add if-elif-else logic to your current projects
- ๐ Learn about match statements (Python 3.10+) for even more power
- ๐ Share your creative conditional logic with others!
Remember: Every complex program started with a simple if statement. Keep coding, keep learning, and most importantly, have fun! ๐
Happy coding! ๐๐โจ