Chapter 12: Conditional Expressions (Ternary Operator)ยถ
๐ Open Notebookยถ
๐บ Video Tutorialยถ
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ยถ
Check if number is positive, negative, or zero
Determine if year is leap year (divisible by 4)
Assign discount based on purchase amount (>100 = 10%, else 0%)
Check if password is strong (length >= 8)
Determine shipping: โFreeโ if total > 50 else โ$5.99โ
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ยถ
Create age category checker (Child/Teen/Adult/Senior)
Build temperature converter with unit check
Make a simple calculator using ternary for operation selection
Create BMI category determiner
Build a simple voting eligibility checker
๐ Key Takeaways from Videoยถ
Variables store data values that can be reused
Use if-elif-else for conditional logic
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!