Yes, Python has a ternary conditional operator (often called a “ternary expression”) that allows you to write simple conditional logic in a single line. Its syntax is:
value_if_true if condition else value_if_false
How It Works
- If
condition
evaluates toTrue
, the expression returnsvalue_if_true
. - If
condition
evaluates toFalse
, it returnsvalue_if_false
.
Example 1: Basic Usage
x = 10
result = "Even" if x % 2 == 0 else "Odd"
print(result) # Output: "Even"
Example 2: Assigning Numeric Values
age = 25
category = "Adult" if age >= 18 else "Minor"
print(category) # Output: "Adult"
Example 3: Nested Ternary (Use Sparingly!)
score = 85
grade = (
"A" if score >= 90 else
"B" if score >= 80 else
"C" if score >= 70 else
"F"
)
print(grade) # Output: "B"
Key Notes
- Order Matters:
The structure is[true_value] if [condition] else [false_value]
(unlike C/JavaScript’scondition ? true_value : false_value
). - Readability:
Use it for simple conditions only. For complex logic, stick toif-elif-else
blocks. - Both Branches Are Required:
Theelse
clause is mandatory. This will throw an error:
# SyntaxError: invalid syntax
value = "Yes" if condition
- Works with All Data Types:
You can return strings, numbers, objects, or even functions:
# Return a function
action = save_data if user_is_valid else log_error
Common Use Cases
- Variable Assignment:
discount = 0.2 if is_member else 0.05
- Function Arguments:
print(f"Status: {'Active' if is_active else 'Inactive'}")
- List Comprehensions:
numbers = [1, 2, 3, 4]
squared = [x**2 if x % 2 == 0 else x for x in numbers]
# Output: [1, 4, 3, 16]
Avoid Misusing It
While ternary expressions are concise, overusing them can hurt readability. Compare:
Good (simple condition):
message = "Success" if status_code == 200 else "Error"
Bad (nested complexity):
# Hard to read! Use `if-elif-else` instead.
result = "A" if x > 90 else "B" if x > 80 else "C" if x > 70 else "F"
Pure JavaScript Comparison
For developers familiar with JavaScript:
// JavaScript
const result = condition ? true_value : false_value;
# Python
result = true_value if condition else false_value
In summary, Python’s ternary operator is a compact way to handle simple conditionals.