Conditional Expressions
The Ternary Operator
Master Python's one-line if/else shorthand: x if condition else y. Write cleaner, more expressive code.
What Is a Conditional Expression?
A conditional expression lets you choose between two values in a single line of code. In many languages this is called a ternary operator because it takes three operands: a value if true, a condition, and a value if false.
It evaluates the condition first. If the condition is truthy, the expression returns the left value. Otherwise, it returns the right value.
Why Use Ternary Expressions?
Anatomy of the Syntax
The Core Rule
# General form result = A if condition else B # Equivalent if/else block if condition: result = A else: result = B
How Evaluation Flows
Expression vs Statement
| Ternary Expression | if/else Statement | |
|---|---|---|
| Lines of code | 1 line | 4 lines |
| Returns a value? | ✓ Yes | No (performs action) |
| Usable inside assignment | ✓ Directly | Must assign in each branch |
| Best for | Simple 2-way choices | Complex logic, multi-step |
| Readability risk | Nesting gets messy | Clear at any complexity |
How to Write One: Step by Step
Example 1: Basic Assignment
age = 20 label = "adult" if age >= 18 else "minor" print(label) # Output: adult
# Same logic as a full if/else: if age >= 18: label = "adult" else: label = "minor"
Example 2: Inside a Return Statement
def abs_value(n): return n if n >= 0 else -n print(abs_value(-7)) # Output: 7 print(abs_value(5)) # Output: 5
Example 3: Inside an f-string
score = 85 msg = f"You {'passed' if score >= 60 else 'failed'} the exam." print(msg) # Output: You passed the exam.
# Also works in list comprehensions: nums = [1, -3, 4, -2] signs = ["+" if x >= 0 else "-" for x in nums] # ['+', '-', '+', '-']
Example 4: Nested Ternaries (Use Sparingly)
x = 0 sign = "positive" if x > 0 else ("negative" if x < 0 else "zero") print(sign) # Output: zero
# Cleaner alternative: if x > 0: sign = "positive" elif x < 0: sign = "negative" else: sign = "zero"
Common Use Cases
Truthiness in Python
The condition in a ternary doesn't have to be a comparison. Python evaluates any object's truthiness. Knowing what's falsy prevents bugs.
items = [] msg = "Has items" if items else "Empty" # "Empty" — because [] is falsy
Common Mistakes
Quick Reference Summary
| Feature | Details |
|---|---|
| Syntax | A if condition else B |
| Returns | A when True, B when False |
| Type | Expression (produces a value) |
| Works inside | Assignments, returns, f-strings, list comps |
| Nesting | Possible but discouraged |
| Best practice | Keep it short and simple |
Question 1 of 5
What does the following expression evaluate to?
"even" if \(7 % 2 == 0\) else "odd"
Question 2 of 5
Which of these is the correct Python ternary syntax?
Question 3 of 5
What is the output of this code?
x = 0
print("yes" if x else "no")
Question 4 of 5
Why does result = "ok" if True cause a SyntaxError?
Question 5 of 5
What does this list comprehension produce?
["even" if \(n % 2 == 0\) else "odd" for n in [1, 2, 3]]