Chapter 12: Conditional Expressions (Ternary Operator)ยถ

๐Ÿš€ Open Notebookยถ

Open In Colab Open In Kaggle

๐Ÿ“บ Video Tutorialยถ

Watch on YouTube

Learn conditional expressions in 5 minutes! โ“ (5:21)

๐Ÿ“š What Youโ€™ll Learnยถ

Write compact, elegant one-line conditional statements using Pythonโ€™s ternary operator!

๐ŸŽฏ Learning Objectivesยถ

  • Understand the ternary operator syntax

  • Convert if-else statements to one-liners

  • Know when to use ternary vs traditional if-else

  • Write cleaner, more pythonic code

๐Ÿ“– Concept Explanationยถ

What is a Ternary Operator?ยถ

A ternary operator (conditional expression) is a compact way to write simple if-else statements in one line.

Syntaxยถ

value_if_true if condition else value_if_false

Traditional vs Ternaryยถ

# Traditional if-else
if age >= 18:
    status = "Adult"
else:
    status = "Minor"

# Ternary operator (one line)
status = "Adult" if age >= 18 else "Minor"

๐Ÿ’ก Examplesยถ

Example 1: Even or Oddยถ

number = 7
result = "EVEN" if number % 2 == 0 else "ODD"
print(result)  # Output: ODD

Example 2: Max of Two Numbersยถ

a, b = 15, 23
maximum = a if a > b else b
print(f"Max: {maximum}")  # Output: Max: 23

Example 3: Pass/Failยถ

score = 75
result = "PASS" if score >= 60 else "FAIL"
print(result)  # Output: PASS

Example 4: Access Levelยถ

user_role = "admin"
access = "Full Access" if user_role == "admin" else "Limited Access"
print(access)  # Output: Full Access

โœ๏ธ Practice Exercisesยถ

  1. Check if number is positive, negative, or zero

  2. Determine if year is leap year (divisible by 4)

  3. Assign discount based on purchase amount (>100 = 10%, else 0%)

  4. Check if password is strong (length >= 8)

  5. Determine shipping: โ€œFreeโ€ if total > 50 else โ€œ$5.99โ€

  6. Set temperature message: โ€œColdโ€ if temp < 60 else โ€œWarmโ€

๐Ÿ” When to Useยถ

โœ… Good Use Casesยถ

# Simple value assignment
status = "Open" if is_open else "Closed"

# Function arguments
print("Hello" if is_greeting else "Goodbye")

# List/dict values
data = {"status": "active" if user.is_active else "inactive"}

# Return statements
return True if value > 0 else False

โŒ Avoid Ternary Forยถ

# Complex logic (use regular if-else)
result = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"
# Too hard to read!

# Multiple statements
message = (print("Hello"), user.save(), "Done") if condition else "Skip"
# Not allowed - ternary is for expressions, not statements

๐Ÿ“ Nested Ternary (Use Sparingly!)ยถ

# Can be hard to read
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"

# Better: use regular if-elif-else for multiple conditions
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

๐ŸŽฎ Real-World Examplesยถ

Example: Discount Calculatorยถ

total = 120
discount = 0.10 if total >= 100 else 0.05 if total >= 50 else 0
savings = total * discount
final = total - savings
print(f"Discount: {discount*100}%, You save: ${savings:.2f}")

Example: User Status Badgeยถ

points = 1500
badge = "๐Ÿฅ‡ Gold" if points >= 1000 else "๐Ÿฅˆ Silver" if points >= 500 else "๐Ÿฅ‰ Bronze"
print(f"Your badge: {badge}")

๐Ÿš€ Try It Yourselfยถ

  1. Create age category checker (Child/Teen/Adult/Senior)

  2. Build temperature converter with unit check

  3. Make a simple calculator using ternary for operation selection

  4. Create BMI category determiner

  5. Build a simple voting eligibility checker

๐ŸŽ“ Key Takeaways from Videoยถ

  1. Variables store data values that can be reused

  2. Use if-elif-else for conditional logic

  3. Follow along with the video for hands-on practice

๐Ÿ’ก These points cover the main concepts from the video tutorial to help reinforce your learning.

๐Ÿ”— Next Chapterยถ

Continue to Chapter 13: String Methods to explore string manipulation techniques!