+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Part 44 of 365

๐Ÿ“˜ Ternary Operator: Conditional Expressions

Master ternary operator: conditional expressions 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 the ternary operator in Python! ๐ŸŽ‰ Have you ever wished you could write if-else statements in a single, elegant line? Thatโ€™s exactly what the ternary operator (also called conditional expressions) lets you do!

Youโ€™ll discover how this powerful Python feature can make your code more concise and readable. Whether youโ€™re validating user input ๐Ÿ“, setting default values ๐ŸŽฏ, or making quick decisions in your code ๐Ÿค”, the ternary operator is your new best friend!

By the end of this tutorial, youโ€™ll be writing cleaner, more Pythonic code that will impress your fellow developers! Letโ€™s dive in! ๐ŸŠโ€โ™‚๏ธ

๐Ÿ“š Understanding Ternary Operators

๐Ÿค” What is a Ternary Operator?

The ternary operator is like a traffic light for your code ๐Ÿšฆ. It helps you make quick decisions: if the light is green (condition is True), go one way; if itโ€™s red (condition is False), go another way!

In Python terms, the ternary operator is a one-line shorthand for simple if-else statements. This means you can:

  • โœจ Write cleaner, more concise code
  • ๐Ÿš€ Make quick conditional assignments
  • ๐Ÿ›ก๏ธ Reduce code complexity for simple decisions

๐Ÿ’ก Why Use Ternary Operators?

Hereโ€™s why developers love ternary operators:

  1. Conciseness ๐Ÿ“: Turn 4 lines into 1 line
  2. Readability ๐Ÿ‘€: For simple conditions, itโ€™s easier to read
  3. Functional Style ๐ŸŽจ: Perfect for lambda functions and comprehensions
  4. Variable Assignment ๐Ÿ“ฆ: Set values based on conditions instantly

Real-world example: Imagine building a game ๐ŸŽฎ. With ternary operators, you can quickly set player status: status = "Winner! ๐Ÿ†" if score >= 100 else "Keep trying! ๐Ÿ’ช"

๐Ÿ”ง Basic Syntax and Usage

๐Ÿ“ The Classic Syntax

Letโ€™s start with the fundamental pattern:

# ๐Ÿ‘‹ Hello, Ternary Operator!
# Basic syntax: value_if_true if condition else value_if_false

# ๐ŸŽฏ Simple example
age = 18
message = "Welcome! ๐ŸŽ‰" if age >= 18 else "Sorry, too young ๐Ÿ‘ถ"
print(message)  # Output: Welcome! ๐ŸŽ‰

# ๐ŸŒก๏ธ Temperature check
temperature = 25
weather = "Nice day! โ˜€๏ธ" if temperature > 20 else "Bit chilly! ๐Ÿงฅ"
print(weather)  # Output: Nice day! โ˜€๏ธ

# ๐ŸŽฎ Game score
score = 85
grade = "Pass โœ…" if score >= 60 else "Fail โŒ"
print(grade)  # Output: Pass โœ…

๐Ÿ’ก Explanation: The ternary operator evaluates the condition first. If True, it returns the first value; if False, it returns the second value. Simple as that!

๐ŸŽฏ Common Patterns

Here are patterns youโ€™ll use daily:

# ๐Ÿ—๏ธ Pattern 1: Setting default values
user_input = ""  # Empty input
name = user_input if user_input else "Anonymous ๐Ÿฆธ"
print(f"Hello, {name}!")  # Output: Hello, Anonymous ๐Ÿฆธ!

# ๐ŸŽจ Pattern 2: Number comparisons
x, y = 10, 20
max_value = x if x > y else y
min_value = x if x < y else y
print(f"Max: {max_value}, Min: {min_value}")  # Output: Max: 20, Min: 10

# ๐Ÿ”„ Pattern 3: Boolean conversion
is_active = True
status = "Active ๐ŸŸข" if is_active else "Inactive ๐Ÿ”ด"
print(status)  # Output: Active ๐ŸŸข

# ๐ŸŽฏ Pattern 4: Nested ternary (use sparingly!)
score = 95
grade = "A+ ๐ŸŒŸ" if score >= 90 else ("B ๐Ÿ˜Š" if score >= 80 else "C ๐Ÿ“š")
print(f"Your grade: {grade}")  # Output: Your grade: A+ ๐ŸŒŸ

๐Ÿ’ก Practical Examples

๐Ÿ›’ Example 1: Shopping Cart Discount System

Letโ€™s build something real:

# ๐Ÿ›๏ธ Smart discount calculator
class ShoppingCart:
    def __init__(self):
        self.items = []
        self.total = 0
    
    def add_item(self, name, price):
        # ๐Ÿ“ฆ Add item to cart
        self.items.append({"name": name, "price": price})
        self.total += price
        print(f"Added {name} to cart! ๐Ÿ›’")
    
    def calculate_discount(self):
        # ๐Ÿ’ฐ Ternary magic for discounts!
        discount = 0.20 if self.total >= 100 else (0.10 if self.total >= 50 else 0)
        discount_amount = self.total * discount
        final_price = self.total - discount_amount
        
        # ๐ŸŽŠ Display message based on discount
        message = "Mega discount! ๐ŸŽ‰" if discount >= 0.20 else ("Nice savings! ๐Ÿ’ต" if discount > 0 else "No discount yet ๐Ÿ›๏ธ")
        
        return {
            "subtotal": self.total,
            "discount": f"{int(discount * 100)}%",
            "savings": discount_amount,
            "final": final_price,
            "message": message
        }
    
    def checkout(self):
        # ๐Ÿงพ Show final bill
        result = self.calculate_discount()
        print(f"\n๐Ÿงพ Your Bill:")
        print(f"Subtotal: ${result['subtotal']:.2f}")
        print(f"Discount: {result['discount']} (-${result['savings']:.2f})")
        print(f"Total: ${result['final']:.2f}")
        print(f"{result['message']}")

# ๐ŸŽฎ Let's shop!
cart = ShoppingCart()
cart.add_item("Python Book ๐Ÿ“˜", 45)
cart.add_item("Coffee โ˜•", 15)
cart.add_item("Mechanical Keyboard โŒจ๏ธ", 85)
cart.checkout()

๐ŸŽฏ Try it yourself: Add a VIP membership feature that gives extra discounts!

๐ŸŽฎ Example 2: RPG Character Status System

Letโ€™s make it fun with a game example:

# ๐Ÿ† RPG character status manager
class RPGCharacter:
    def __init__(self, name):
        self.name = name
        self.health = 100
        self.mana = 50
        self.level = 1
        self.experience = 0
    
    def take_damage(self, damage):
        # ๐Ÿ›ก๏ธ Apply damage with ternary protection
        self.health = max(0, self.health - damage)
        status = "Knocked out! ๐Ÿ’ซ" if self.health == 0 else ("Critical! ๐Ÿฉธ" if self.health < 20 else "Still fighting! โš”๏ธ")
        print(f"{self.name} takes {damage} damage! {status}")
        return self.health > 0  # Returns True if still alive
    
    def heal(self, amount):
        # ๐Ÿ’š Healing with limits
        old_health = self.health
        self.health = min(100, self.health + amount)
        healed = self.health - old_health
        message = "Full health! ๐Ÿ’ช" if self.health == 100 else f"Healed {healed} HP! โœจ"
        print(message)
    
    def gain_exp(self, exp):
        # ๐Ÿ“ˆ Experience and leveling
        self.experience += exp
        exp_needed = self.level * 100
        
        # ๐ŸŽŠ Level up check with ternary
        level_up = self.experience >= exp_needed
        self.level = self.level + 1 if level_up else self.level
        self.experience = self.experience - exp_needed if level_up else self.experience
        
        message = f"LEVEL UP! Now level {self.level} ๐ŸŽ‰" if level_up else f"Gained {exp} XP ๐ŸŒŸ"
        print(message)
    
    def get_status(self):
        # ๐ŸŽฏ Character status with multiple ternary operators
        health_status = "Healthy ๐Ÿ’š" if self.health > 70 else ("Wounded ๐ŸŸก" if self.health > 30 else "Critical ๐Ÿ”ด")
        mana_status = "Full Power ๐Ÿ”ต" if self.mana > 30 else "Low Mana โšช"
        
        print(f"\n๐Ÿ“Š {self.name}'s Status:")
        print(f"Level: {self.level} โญ")
        print(f"Health: {self.health}/100 - {health_status}")
        print(f"Mana: {self.mana}/50 - {mana_status}")
        print(f"XP: {self.experience}/{self.level * 100} ๐Ÿ“ˆ")

# ๐ŸŽฎ Adventure time!
hero = RPGCharacter("PyWarrior")
hero.get_status()

# ๐Ÿ—ก๏ธ Battle sequence
hero.take_damage(30)
hero.take_damage(55)
hero.heal(40)
hero.gain_exp(120)
hero.get_status()

๐ŸŒก๏ธ Example 3: Smart Home Temperature Controller

A practical IoT example:

# ๐Ÿ  Smart home temperature controller
class SmartThermostat:
    def __init__(self):
        self.current_temp = 20  # Celsius
        self.target_temp = 22
        self.is_home = True
        self.is_night = False
    
    def adjust_temperature(self, outside_temp):
        # ๐ŸŒก๏ธ Smart adjustments with ternary operators
        # Eco mode when not home
        eco_mode = not self.is_home
        target = 18 if eco_mode else (19 if self.is_night else self.target_temp)
        
        # ๐Ÿ”„ Heating or cooling decision
        action = "Heating ๐Ÿ”ฅ" if self.current_temp < target else ("Cooling โ„๏ธ" if self.current_temp > target else "Stable โœ…")
        
        # ๐Ÿ’จ Fan speed based on temperature difference
        diff = abs(self.current_temp - target)
        fan_speed = "High ๐Ÿ’จ๐Ÿ’จ๐Ÿ’จ" if diff > 5 else ("Medium ๐Ÿ’จ๐Ÿ’จ" if diff > 2 else "Low ๐Ÿ’จ")
        
        # ๐Ÿ’ฐ Energy saving mode
        energy_mode = "Eco ๐ŸŒฟ" if eco_mode else ("Night ๐ŸŒ™" if self.is_night else "Comfort โ˜€๏ธ")
        
        return {
            "action": action,
            "fan": fan_speed,
            "mode": energy_mode,
            "target": target
        }
    
    def simulate_hour(self):
        # โฐ Simulate temperature changes
        settings = self.adjust_temperature(15)  # 15ยฐC outside
        
        # ๐Ÿ“Š Update temperature based on action
        self.current_temp += 1 if settings["action"] == "Heating ๐Ÿ”ฅ" else (-1 if settings["action"] == "Cooling โ„๏ธ" else 0)
        
        print(f"\n๐Ÿ  Smart Home Status:")
        print(f"Current: {self.current_temp}ยฐC | Target: {settings['target']}ยฐC")
        print(f"Action: {settings['action']} | Fan: {settings['fan']}")
        print(f"Mode: {settings['mode']}")

# ๐ŸŽฏ Test the system
thermostat = SmartThermostat()
thermostat.current_temp = 25  # Hot day

# Simulate different scenarios
print("๐Ÿ“… Daytime - At Home:")
thermostat.simulate_hour()

print("\n๐ŸŒ™ Nighttime:")
thermostat.is_night = True
thermostat.simulate_hour()

print("\n๐Ÿš— Away from home:")
thermostat.is_home = False
thermostat.simulate_hour()

๐Ÿš€ Advanced Concepts

๐Ÿง™โ€โ™‚๏ธ Advanced Topic 1: Chained Ternary Operators

When youโ€™re ready to level up, try chaining ternary operators (but use with caution!):

# ๐ŸŽฏ Grade calculator with multiple conditions
def calculate_grade(score):
    # ๐ŸŽ“ Chained ternary for grade boundaries
    return (
        "A+ ๐ŸŒŸ" if score >= 95 else
        "A ๐ŸŽฏ" if score >= 90 else
        "B+ ๐Ÿ“š" if score >= 85 else
        "B ๐Ÿ“–" if score >= 80 else
        "C+ ๐Ÿ“" if score >= 75 else
        "C ๐Ÿ“„" if score >= 70 else
        "D ๐Ÿ˜…" if score >= 60 else
        "F ๐Ÿ˜ข"
    )

# ๐Ÿงช Test the grading system
scores = [98, 92, 87, 82, 76, 71, 65, 55]
for score in scores:
    grade = calculate_grade(score)
    print(f"Score: {score} โ†’ Grade: {grade}")

# ๐ŸŽจ Color picker based on temperature
def get_temperature_color(temp):
    # ๐ŸŒˆ Temperature to color mapping
    return (
        "๐Ÿ”ด Red Hot!" if temp >= 35 else
        "๐ŸŸ  Orange Warm" if temp >= 28 else
        "๐ŸŸก Yellow Pleasant" if temp >= 22 else
        "๐ŸŸข Green Mild" if temp >= 15 else
        "๐Ÿ”ต Blue Cool" if temp >= 8 else
        "๐ŸŸฃ Purple Cold" if temp >= 0 else
        "โšช White Freezing"
    )

๐Ÿ—๏ธ Advanced Topic 2: Ternary in Comprehensions

Combine ternary operators with list comprehensions for powerful one-liners:

# ๐Ÿš€ List comprehension with ternary
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# ๐ŸŽฏ Even/odd labeling
labeled = [f"{n} (even ๐ŸŸข)" if n % 2 == 0 else f"{n} (odd ๐Ÿ”ต)" for n in numbers]
print("Numbers:", labeled[:5])  # Show first 5

# ๐Ÿ† Score processing
scores = [45, 78, 92, 67, 88, 55, 95, 71]
results = ["Pass โœ…" if score >= 60 else "Fail โŒ" for score in scores]
print("\nResults:", results)

# ๐Ÿ’ฐ Price formatting with discounts
prices = [10, 25, 50, 75, 100, 150]
discounted = [
    f"${p * 0.8:.2f} (20% off! ๐ŸŽ‰)" if p >= 100 else 
    f"${p * 0.9:.2f} (10% off! ๐Ÿ’ต)" if p >= 50 else 
    f"${p:.2f}"
    for p in prices
]
print("\nPrices:", discounted)

# ๐ŸŽฎ Dictionary comprehension with ternary
players = ["Alice", "Bob", "Charlie", "Diana", "Eve"]
player_scores = {85, 45, 92, 67, 78}
leaderboard = {
    player: "Champion ๐Ÿ†" if score >= 90 else ("Veteran โญ" if score >= 70 else "Rookie ๐ŸŒฑ")
    for player, score in zip(players, player_scores)
}
print("\nLeaderboard:", dict(list(leaderboard.items())[:3]))

๐Ÿช„ Advanced Topic 3: Ternary with Functions

Use ternary operators with function calls and lambda expressions:

# ๐ŸŽฏ Function selection with ternary
def greet_formal(name):
    return f"Good day, Mr./Ms. {name} ๐ŸŽฉ"

def greet_casual(name):
    return f"Hey {name}! What's up? ๐Ÿ˜Ž"

# ๐Ÿค Dynamic greeting
is_formal_event = True
greet = greet_formal if is_formal_event else greet_casual
print(greet("Python"))

# ๐Ÿ”„ Lambda with ternary
process = lambda x: x ** 2 if x > 0 else 0
numbers = [-3, -1, 0, 2, 5]
processed = [process(n) for n in numbers]
print(f"\nProcessed: {processed}")

# ๐ŸŽจ Multiple operations
def apply_operation(value, operation):
    # ๐Ÿงฎ Choose operation with ternary
    return (
        value * 2 if operation == "double" else
        value ** 2 if operation == "square" else
        value / 2 if operation == "halve" else
        value  # default: return unchanged
    )

# ๐Ÿงช Test operations
ops = ["double", "square", "halve", "unknown"]
for op in ops:
    result = apply_operation(10, op)
    emoji = "โœ–๏ธ2" if op == "double" else ("ยฒ" if op == "square" else ("โž—2" if op == "halve" else "โ“"))
    print(f"10 {emoji} = {result}")

โš ๏ธ Common Pitfalls and Solutions

๐Ÿ˜ฑ Pitfall 1: Overcomplicating with Nested Ternaries

# โŒ Wrong way - nested ternary nightmare!
age = 25
category = "baby ๐Ÿ‘ถ" if age < 2 else ("toddler ๐Ÿง’" if age < 5 else ("child ๐Ÿ‘ฆ" if age < 13 else ("teen ๐Ÿ‘ฆ" if age < 20 else ("adult ๐Ÿ‘จ" if age < 65 else "senior ๐Ÿ‘ด"))))
# This is hard to read and maintain! ๐Ÿ˜ต

# โœ… Correct way - use a function with clear if-elif
def get_age_category(age):
    if age < 2:
        return "baby ๐Ÿ‘ถ"
    elif age < 5:
        return "toddler ๐Ÿง’"
    elif age < 13:
        return "child ๐Ÿ‘ฆ"
    elif age < 20:
        return "teen ๐Ÿง‘"
    elif age < 65:
        return "adult ๐Ÿ‘จ"
    else:
        return "senior ๐Ÿ‘ด"

category = get_age_category(25)
print(f"Category: {category}")  # Much cleaner! โœจ

๐Ÿคฏ Pitfall 2: Side Effects in Ternary Expressions

# โŒ Dangerous - side effects in ternary!
count = 0

def increment():
    global count
    count += 1
    return count

# This will always increment, even when not needed!
result = increment() if True else increment()  # ๐Ÿ’ฅ Confusing!

# โœ… Safe way - evaluate conditions separately
count = 0
if condition:
    result = increment()
else:
    result = some_other_value

# โœ… Or use ternary only for values
value1 = 10
value2 = 20
result = value1 if condition else value2  # Clean! โœจ

๐Ÿ› Pitfall 3: Forgetting Operator Precedence

# โŒ Wrong - precedence confusion
x = 5
y = 10
# This doesn't do what you think!
result = x + 1 if x > 3 else y + 1
print(result)  # Outputs: 6 (not 11!)

# โœ… Correct - use parentheses for clarity
result = (x + 1) if x > 3 else (y + 1)
print(result)  # Clear intention! โœจ

# ๐ŸŽฏ More examples of precedence
# โŒ Confusing
message = "Score: " + "High" if score > 80 else "Low"  # Error!

# โœ… Clear
message = "Score: " + ("High" if score > 80 else "Low")  # Works! ๐ŸŽ‰

๐Ÿ› ๏ธ Best Practices

  1. ๐ŸŽฏ Keep It Simple: Use ternary only for simple conditions
  2. ๐Ÿ“ Readability First: If itโ€™s hard to read, use if-else
  3. ๐Ÿ›ก๏ธ Avoid Nesting: Maximum one level of nesting
  4. ๐ŸŽจ Consistent Style: Pick a style and stick to it
  5. โœจ Value Assignment: Best used for assigning values, not complex logic
# ๐ŸŒŸ Good practices examples
# โœ… Simple value assignment
status = "active" if user.is_logged_in else "inactive"

# โœ… Default values
name = user_input or "Anonymous"  # Even simpler than ternary!

# โœ… Return statements
def get_discount(member_type):
    return 0.20 if member_type == "gold" else 0.10

# โœ… String formatting
print(f"Status: {'Online ๐ŸŸข' if is_connected else 'Offline ๐Ÿ”ด'}")

# โŒ Avoid complex logic
# Don't do this in ternary!
# result = (complex_function() if condition1 and condition2 
#          and not condition3 else other_complex_function())

๐Ÿงช Hands-On Exercise

๐ŸŽฏ Challenge: Build a Movie Rating System

Create a movie rating system using ternary operators:

๐Ÿ“‹ Requirements:

  • โœ… Rate movies from 1-10 stars
  • ๐Ÿท๏ธ Categorize as โ€œMust Watchโ€, โ€œGoodโ€, โ€œAverageโ€, or โ€œSkipโ€
  • ๐Ÿ‘ค Track viewer age for content warnings
  • ๐Ÿ“… Show if movie is new release (< 30 days)
  • ๐ŸŽจ Each rating needs an emoji!

๐Ÿš€ Bonus Points:

  • Add genre-based recommendations
  • Implement a โ€œsimilar moviesโ€ feature
  • Create a top 10 list with rankings

๐Ÿ’ก Solution

๐Ÿ” Click to see solution
# ๐ŸŽฌ Movie Rating System
from datetime import datetime, timedelta

class Movie:
    def __init__(self, title, rating, genre, release_date, age_rating="PG"):
        self.title = title
        self.rating = rating
        self.genre = genre
        self.release_date = release_date
        self.age_rating = age_rating
    
    def get_category(self):
        # ๐ŸŒŸ Categorize based on rating
        return (
            "Must Watch! ๐Ÿ†" if self.rating >= 8.5 else
            "Great Movie ๐ŸŒŸ" if self.rating >= 7 else
            "Worth Watching ๐Ÿ‘" if self.rating >= 5.5 else
            "Skip It ๐Ÿ‘Ž"
        )
    
    def is_new_release(self):
        # ๐Ÿ“… Check if movie is new (< 30 days)
        days_old = (datetime.now() - self.release_date).days
        return days_old < 30
    
    def get_emoji(self):
        # ๐ŸŽญ Genre-based emojis
        emoji_map = {
            "Action": "๐Ÿ’ฅ", "Comedy": "๐Ÿ˜‚", "Drama": "๐ŸŽญ",
            "Horror": "๐Ÿ‘ป", "Romance": "๐Ÿ’•", "Sci-Fi": "๐Ÿš€"
        }
        return emoji_map.get(self.genre, "๐ŸŽฌ")
    
    def can_watch(self, viewer_age):
        # ๐Ÿ‘ค Age restriction check
        age_limits = {"G": 0, "PG": 0, "PG-13": 13, "R": 17}
        required_age = age_limits.get(self.age_rating, 18)
        return viewer_age >= required_age
    
    def display_info(self, viewer_age=18):
        # ๐Ÿ“บ Display movie information
        new_badge = "๐Ÿ†• NEW!" if self.is_new_release() else ""
        can_view = "โœ… Can watch" if self.can_watch(viewer_age) else "๐Ÿšซ Age restricted"
        
        print(f"\n{self.get_emoji()} {self.title} {new_badge}")
        print(f"Rating: {self.rating}/10 โญ - {self.get_category()}")
        print(f"Genre: {self.genre} | Age: {self.age_rating}")
        print(f"Access: {can_view}")

class MovieRecommender:
    def __init__(self):
        self.movies = []
    
    def add_movie(self, movie):
        self.movies.append(movie)
    
    def get_top_movies(self, count=10):
        # ๐Ÿ† Get top-rated movies
        sorted_movies = sorted(self.movies, key=lambda m: m.rating, reverse=True)
        return sorted_movies[:count]
    
    def recommend_similar(self, movie):
        # ๐ŸŽฏ Find similar movies by genre
        similar = [m for m in self.movies 
                  if m.genre == movie.genre and m.title != movie.title]
        # Sort by rating
        similar.sort(key=lambda m: m.rating, reverse=True)
        
        return similar[:3] if similar else []
    
    def display_top_10(self):
        # ๐Ÿ“Š Display top 10 movies
        print("\n๐Ÿ† TOP 10 MOVIES ๐Ÿ†")
        print("=" * 40)
        
        for i, movie in enumerate(self.get_top_movies(), 1):
            medal = "๐Ÿฅ‡" if i == 1 else ("๐Ÿฅˆ" if i == 2 else ("๐Ÿฅ‰" if i == 3 else f"#{i}"))
            new = " ๐Ÿ†•" if movie.is_new_release() else ""
            print(f"{medal} {movie.title} ({movie.rating}โญ){new}")

# ๐ŸŽฌ Create movie database
recommender = MovieRecommender()

# Add movies
movies_data = [
    ("The Python Chronicles", 9.2, "Sci-Fi", datetime.now() - timedelta(days=10), "PG-13"),
    ("Loops of Fury", 8.7, "Action", datetime.now() - timedelta(days=45), "R"),
    ("Variable Hearts", 7.5, "Romance", datetime.now() - timedelta(days=20), "PG"),
    ("Exception Handler", 8.9, "Action", datetime.now() - timedelta(days=5), "PG-13"),
    ("The Big O Notation", 6.8, "Comedy", datetime.now() - timedelta(days=60), "PG"),
]

for data in movies_data:
    movie = Movie(*data)
    recommender.add_movie(movie)
    movie.display_info(viewer_age=15)

# ๐ŸŽฏ Test recommendations
print("\n๐ŸŽฌ Similar to 'The Python Chronicles':")
similar = recommender.recommend_similar(recommender.movies[0])
for movie in similar:
    print(f"  โ†’ {movie.get_emoji()} {movie.title} ({movie.rating}โญ)")

# ๐Ÿ† Show top 10
recommender.display_top_10()

๐ŸŽ“ Key Takeaways

Youโ€™ve mastered the ternary operator! Hereโ€™s what you can now do:

  • โœ… Write concise conditional expressions with confidence ๐Ÿ’ช
  • โœ… Choose between ternary and if-else appropriately ๐Ÿ›ก๏ธ
  • โœ… Avoid common ternary pitfalls that trip up beginners ๐ŸŽฏ
  • โœ… Use ternary in comprehensions like a pro ๐Ÿ›
  • โœ… Create cleaner, more Pythonic code with ternary operators! ๐Ÿš€

Remember: The ternary operator is a tool, not a replacement for all if-else statements. Use it wisely! ๐Ÿค

๐Ÿค Next Steps

Congratulations! ๐ŸŽ‰ Youโ€™ve mastered the ternary operator in Python!

Hereโ€™s what to do next:

  1. ๐Ÿ’ป Practice with the movie rating exercise above
  2. ๐Ÿ—๏ธ Refactor some of your old if-else statements to use ternary
  3. ๐Ÿ“š Move on to our next tutorial: Lambda Functions
  4. ๐ŸŒŸ Share your newfound ternary skills with fellow Pythonistas!

Remember: Clean code is happy code. The ternary operator is just one tool in your Python toolbox. Use it when it makes your code clearer, not just shorter! ๐Ÿš€


Happy coding! ๐ŸŽ‰๐Ÿโœจ