01 / 21
? x y

Conditional Expressions
The Ternary Operator

Master Python's one-line if/else shorthand: x if condition else y. Write cleaner, more expressive code.

Python

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?

Conciseness
Replace 4 lines of if/else with a single, readable expression.
Inline Usage
Embed decisions directly inside assignments, return statements, and f-strings.
Readability
Simple conditions stay clean without indentation blocks cluttering your logic.

Anatomy of the Syntax

result = x if condition else y Value if True Boolean Condition (evaluated first) Value if False Stores the result Reads left-to-right: "x IF condition ELSE y"

The Core Rule

# General form
result = A if condition else B

# Equivalent if/else block
if condition:
    result = A
else:
    result = B
Expression
Returns a value. Can be used anywhere a value is expected: assignments, arguments, lists.
Statement
The traditional if/else is a statement: it performs an action but doesn't produce a value by itself.

How Evaluation Flows

condition True or False? True Return A False Return B result

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

1
Identify the condition. What boolean test determines the outcome? e.g., age \(\geq\) 18
2
Pick the True value. What should be returned when the condition holds? e.g., "adult"
3
Pick the False value. What is the fallback? e.g., "minor"
4
Assemble. Write: "adult" if age \(\geq\) 18 else "minor"
5
Readability check. Read it aloud. If it sounds awkward, use a regular if/else.

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

Default Values
name = user_input if user_input else "Guest"
Clamping
val = x if x \(\leq\) max_val else max_val
Pluralization
f"{n} item{'s' if n \(\neq\) 1 else ''}"

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.

Falsy Values
False, 0, 0.0, "", [], {}, None
Truthy Values
Everything else: non-zero numbers, non-empty strings, non-empty containers, objects
items = []
msg = "Has items" if items else "Empty"
# "Empty" — because [] is falsy

Common Mistakes

✕ Wrong Order
Attempting C-style syntax like condition ? x : y. Python's syntax is more readable, placing the condition in the middle: x if condition else y.
✕ Missing else
Writing x if cond without the else clause. A ternary always requires an else branch.
✕ Over-Nesting
Chaining 3+ ternaries deep. This becomes unreadable. Use if/elif/else for multi-branch logic.

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]]