+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Part 42 of 365

๐Ÿ“˜ If-Elif-Else: Multiple Conditions

Master if-elif-else: multiple conditions in Python with practical examples, best practices, and real-world applications ๐Ÿš€

๐ŸŒฑBeginner
25 min read

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:

  1. Clear Decision Making ๐ŸŽฏ: Handle complex logic elegantly
  2. Readable Code ๐Ÿ“–: Easy to understand the flow
  3. Efficient Execution โšก: Stops checking once a condition is met
  4. 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

  1. ๐ŸŽฏ Order Conditions Properly: Most specific conditions first!
  2. ๐Ÿ“ Keep It Readable: Donโ€™t nest too deeply (max 3 levels)
  3. ๐Ÿ›ก๏ธ Always Include else: Handle unexpected cases
  4. ๐ŸŽจ Use Clear Conditions: Make logic obvious
  5. โœจ 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:

  1. ๐Ÿ’ป Practice with the movie ticket exercise above
  2. ๐Ÿ—๏ธ Add if-elif-else logic to your current projects
  3. ๐Ÿ“š Learn about match statements (Python 3.10+) for even more power
  4. ๐ŸŒŸ 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! ๐ŸŽ‰๐Ÿโœจ