Chapter 2: Control Flow / Lesson 14

Ternary Operator

Ternary Operator (Conditional Expressions)

The ternary operator, also known as a conditional expression, is a concise way to assign a value based on a condition. It's perfect for simple if-else logic in a single line.

Python's ternary operator syntax is: value_if_true if condition else value_if_false

Basic Ternary Operator

The simplest use case is assigning a value based on a condition:

ternary.py
age = 20 status = "Adult" if age >= 18 else "Minor" print(status) # Output: Adult # Equivalent if-else statement: if age >= 18: status = "Adult" else: status = "Minor"

Common Use Cases

Ternary operators are great for simple conditional assignments. Here are some practical examples:

examples.py
# Check if number is even or odd x = 10 result = "Even" if x % 2 == 0 else "Odd" # Find the maximum of two numbers a = 5 b = 10 maximum = a if a > b else b # Set a default value if variable is None name = None display_name = name if name else "Guest" # Check if number is positive, negative, or zero number = -5 sign = "Positive" if number > 0 else ("Negative" if number < 0 else "Zero")

Nested Ternary Operators

You can nest ternary operators for multiple conditions, but be careful - they can become hard to read:

nested.py
score = 85 # Nested ternary (can be hard to read) grade = "A" if score >= 90 else ("B" if score >= 80 else ("C" if score >= 70 else "F")) # Better: Use if-elif-else for complex conditions if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" else: grade = "F"

Using Ternary in Function Calls

Ternary operators are particularly useful when passing values to functions:

function_calls.py
count = 1 item_word = "item" if count == 1 else "items" print(f"You have {count} {item_word}") # Or directly in the f-string print(f"You have {count} {'item' if count == 1 else 'items'}")

Best Practices

✅ Use Ternary For Simple Cases

Use ternary operators for simple, one-line conditional assignments. They make code more concise and readable.

⚠️ Avoid Nested Ternaries

Avoid deeply nested ternary operators. Use if-elif-else statements for complex conditions - they're much more readable.

💡 Readability First

If a ternary operator makes your code harder to understand, use a regular if-else statement instead. Readability is more important than brevity.

Comparison: Ternary vs If-Else

Here's when to use each approach:

comparison.py
# Simple condition - Ternary is perfect status = "Active" if is_active else "Inactive" # Complex condition - Use if-else if age >= 18 and has_license and insurance_valid: status = "Can drive" elif age >= 16: status = "Can learn" else: status = "Too young"
🎉

Lesson Complete!

Great work! Continue to the next lesson.

main.py
📤 Output
Click "Run" to execute...