Python Ternary Operator
In this page:
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
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
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
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
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
use_cache = False
cached_items = ["old"]
fresh_items = ["new"]
items = cached_items if use_cache else fresh_items
print(items)
Chapter Quiz — Complete all 16 topics to unlock
0/16 topics done
Complete these topics first:
- Python print()
- Python input()
- Python Format Strings
- Python f-strings
- Python String Formatting
- Python Arithmetic Operators
- Python Relational Operators
- Python Logical Operators
- Python Bitwise Operators
- Python Assignment Operators
- Python Increment & Decrement
- Python Ternary Operator
- Python Operator Precedence
- Python Identity Operators
- Python Membership Operators
- Python Operators