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:
Common Use Cases
Ternary operators are great for simple conditional assignments. Here are some practical examples:
Nested Ternary Operators
You can nest ternary operators for multiple conditions, but be careful - they can become hard to read:
Using Ternary in Function Calls
Ternary operators are particularly useful when passing values to functions:
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: