7.11 Conditional (Ternary) Operator
Python's one-line conditional expression — value_if_true if condition else value_if_false — and why nested ternaries should stay shallow.
Syntax
What Is It?
A one-line if/else that produces a value rather than executing a statement block: value_if_true if condition else value_if_false.
Why Is It Used?
For simple two-way choices, it’s more compact than a full if/else block.
status = "adult" if age >= 18 else "minor"
# equivalent to:
# if age >= 18:
# status = "adult"
# else:
# status = "minor"
Examples
>>> age = 20
>>> status = "adult" if age >= 18 else "minor"
>>> status
'adult'
Nested Ternary
Chaining ternaries handles more than two outcomes, but readability drops fast past one level of nesting — prefer a full if/elif/else for anything more complex than this.
>>> score = 75
>>> grade = "A" if score >= 90 else "B" if score >= 70 else "C"
>>> grade
'B'
Quick Interview Answer
“The conditional expression
value_if_true if condition else value_if_falseis Python’s ternary operator — it produces a value rather than executing a statement block, unlike a fullif/else. It’s ideal for simple two-way choices assigned to a variable; chaining it for more than two outcomes technically works but readability drops fast, and a fullif/elif/elseblock becomes the better choice past one level of nesting.”
Common Mistakes
- Nesting ternaries two or more levels deep — technically valid, but forces a reader to mentally trace multiple branches on one line.
- Using a ternary purely to save lines when the condition or branches are already complex expressions — readability should win over compactness here (see 7.17 Best Practices).
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form