The Conditional Expression
Python's ternary reads left-to-right like a sentence: value_if_true if condition else value_if_false.
Python has no ?: ternary. Instead it has the conditional expression, which deliberately reads like English:
status = 'adult' if age >= 18 else 'minor'Read it as: "give me 'adult' if age is at least 18, otherwise 'minor'". Because it is an expression (it produces a value), you can use it anywhere a value fits — inside an f-string, a function argument, a list comprehension, or a return statement.
Chaining is legal but risky
You can nest them — a if p else b if q else c — but past one level they become hard to read. When you feel the urge to nest, a small helper function or a match statement is usually clearer.
Not the same as or
The fallback trick name or 'Guest' substitutes for any falsy value (including 0 and ''). A conditional expression lets you test exactly the condition you mean, which is safer when 0 or '' are valid values.
Example
def format_price(amount, currency=None):
# Explicit None check — an empty string currency stays empty on purpose
symbol = currency if currency is not None else '$'
sign = '-' if amount < 0 else ''
return f'{sign}{symbol}{abs(amount):,.2f}'
print(format_price(1999.5)) # $1,999.50
print(format_price(-42, '£')) # -£42.00
print(format_price(0, '')) # 0.00 (empty currency respected)
# Inside a comprehension: label each number
nums = [-3, 0, 7, -1, 4]
labels = ['neg' if n < 0 else 'zero' if n == 0 else 'pos' for n in nums]
print(labels)
# Compare with the 'or' fallback — note how 0 gets clobbered
qty = 0
print('or form :', qty or 5) # 5 (wrong!)
print('explicit form:', qty if qty is not None else 5) # 0 (right)
# Output:
# $1,999.50
# -£42.00
# 0.00
# ['neg', 'zero', 'pos', 'neg', 'pos']
# or form : 5
# explicit form: 0When to use it
- A template renders 'Yes' or 'No' inline using a conditional expression instead of a four-line if/else.
- A default-value assignment picks a fallback string when a variable is empty using a ternary.
- An API response serialiser chooses between two format strings in a list comprehension.
More examples
Basic conditional expression
Assigns one of two string literals based on a condition, all in a single expression.
age = 20
label = 'adult' if age >= 18 else 'minor'
print(label) # adultTernary inside a f-string
Embeds a conditional expression inside an f-string to pluralise 'item' correctly.
items = 3
print(f'You have {items} item{"s" if items != 1 else ""}')
# Output: You have 3 items
items = 1
print(f'You have {items} item{"s" if items != 1 else ""}')
# Output: You have 1 itemTernary in a list comprehension
Uses nested conditional expressions inside a list comprehension to classify each number.
numbers = [-3, 0, 7, -1, 4]
labels = ['pos' if n > 0 else ('zero' if n == 0 else 'neg')
for n in numbers]
print(labels)
# Output: ['neg', 'zero', 'pos', 'neg', 'pos']
Discussion