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

Try it yourself
Loading editor…
Press Run to execute the code.

When 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.

Example · python
age = 20
label = 'adult' if age >= 18 else 'minor'
print(label)   # adult

Ternary inside a f-string

Embeds a conditional expression inside an f-string to pluralise 'item' correctly.

Example · python
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 item

Ternary in a list comprehension

Uses nested conditional expressions inside a list comprehension to classify each number.

Example · python
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

  • Be the first to comment on this lesson.