← Back to Python Course | Chapter 2: Input, Output & Operators | Lesson 12 of 16

Python Ternary Operator

Conditional Expressions

Python's ternary operator is formally called a conditional expression, written as value_if_true if condition else value_if_false — it lets you collapse a short if/else into a single line wherever an expression, not a statement, is expected.

Example: Conditional Expressions

python
age = 20
status = "adult" if age >= 18 else "minor"
print(status)

Checking Even or Odd

A classic use is checking even or odd inline: "even" if n % 2 == 0 else "odd" evaluates the condition once and immediately produces whichever string applies, without a multi-line if block.

Example: Checking Even or Odd

python
n = 7
print("even" if n % 2 == 0 else "odd")

Nested Ternary Expressions

Nesting one conditional expression inside another lets you pick between three or more outcomes, but readability drops fast past one level of nesting — if you need more than two branches, a normal if/elif/else block is usually clearer.

Example: Nested Ternary Expressions

python
score = 75
grade = "A" if score >= 90 else "B" if score >= 70 else "C"
print(grade)

Inline Ternary in Functions

Because a conditional expression is just an expression, it slots neatly into a return statement — return "pass" if score >= 60 else "fail" — letting a function pick its return value in one line instead of a multi-line branch.

Example: Inline Ternary in Functions

python
def result(score):
    return "pass" if score >= 60 else "fail"

print(result(72))

Ternary with Lists

The same pattern works for selecting between two containers, like items = cached_items if use_cache else fresh_items, letting you swap which list or default a variable points to based on a single condition.

Example: Ternary with Lists

python
use_cache = False
cached_items = ["old"]
fresh_items = ["new"]
items = cached_items if use_cache else fresh_items
print(items)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.