A lot of code boils down to "set this variable to one value if a condition is true, or another value otherwise." Writing a full if/else block for that is correct, but it's four lines for what is conceptually a single decision. Python offers a compact alternative called the conditional expression, often referred to by its name in other languages: the ternary operator.

Syntax: value_if_true if condition else value_if_false

age = 20

# The long way, with if/else
if age >= 18:
    status = "adult"
else:
    status = "minor"

# The same logic as a one-line conditional expression
status = "adult" if age >= 18 else "minor"

print(status)

Output:

adult

Read it left to right as: "status is 'adult' if age >= 18, else it's 'minor'." This reads almost like plain English once you're used to the order — note that it's different from most other languages' condition ? true_value : false_value syntax, so if you're coming from JavaScript or Java, expect to read it backward at first.

Using It Inline — Not Just in Assignments

Because a conditional expression evaluates to a value, you can use it anywhere a value is expected — directly inside a print() call, a function argument, or an f-string — not just on the right-hand side of an =.

scores = [45, 82, 91, 58]

for score in scores:
    print(f"Score {score}: {'Pass' if score >= 60 else 'Fail'}")

Output:

Score 45: Fail
Score 82: Pass
Score 91: Pass
Score 58: Fail

This pattern — a conditional expression embedded directly in an f-string inside a for loop — is extremely common in real code, because it avoids a throwaway variable that only exists to hold the pass/fail label for one line.

Chaining Conditional Expressions

You can chain conditional expressions to cover more than two outcomes, similar to elif, though this should be used sparingly:

score = 72
grade = "A" if score >= 90 else "B" if score >= 75 else "C" if score >= 60 else "F"
print(grade)

Output:

C

This works and is valid Python, but it's also a good example of the operator's main weakness.

When It Helps, and When It Hurts

A conditional expression is a readability win when the condition and both branches are short and simple — a single comparison deciding between two short values, as in the pass/fail example above. It becomes a readability loss once you start chaining several of them together, or when either branch involves a nontrivial expression. At that point, a full if/elif/else statement — even though it's longer — is easier for the next reader (including future you) to scan and understand at a glance. A reasonable rule of thumb: if you have to pause and re-read your own conditional expression to confirm what it does, it should probably be a regular if statement instead.