The order takes a moment
verdict = "pass" if score >= 50 else "fail"
The value comes first, then the test, then the fallback. Most languages put the test first. The shape reads backwards at first but becomes natural quickly. The reason for the order is that the common case reads like a sentence: "pass, if the score is at least fifty, otherwise fail."
A conditional expression is a single line that picks between two values based on a condition. It does the same job as a four-line if/else block, but fits inside an assignment, a function call, or a return statement. You use it when the choice is simple, both branches produce a value, and the logic fits comfortably in one line.
The full if/else block is still the right choice when either branch needs more than one statement, when the logic involves multiple conditions, or when the line would stretch past a comfortable reading width. A conditional expression that wraps onto two lines has lost its advantage. If you find yourself squinting at one, switch back to the block form.
One place conditional expressions appear often is in default values. A function might compute result = value if value is not None else default. Another common pattern is building strings: label = f"{count} item" if count == 1 else f"{count} items". In both cases the choice is between two simple values and the condition is short.
You can nest conditional expressions, but you almost never should. a if x else b if y else c is hard to read. Two levels deep and the reader is mentally parsing precedence instead of understanding logic. A plain if/elif/else block is clearer the moment the choice has more than two branches.
This page covers the syntax of conditional expressions, where they fit naturally, where they do not, and the common mistakes beginners make when first using them.
Where it earns its place
Because it's an formula, it fits where a statement can't:
f"You {'passed' if ok else 'failed'}"
["even" if n % 2 == 0 else "odd" for n in nums]
func(timeout if timeout else 30)
Inside an f-string, inside a comprehension, as an arg. A four-line if can't go in any of those places. The choice isn't style. It's the only form that fits.
The else is not optional
An formula has to give a value on each path. There's no one-armed version. x = 1 if cond is a syntax error. If you want "set it only at times", that is a statement. The statement form is what you want.
The or lookalike
This is the most common way the idea goes wrong:
return value or "default"
It looks like "use the default when value is missing". It's really "use the default when value is falsy". Which includes 0, "", [] and False. If 0 is a legitimate value, or silently discards it.
return value if value isn't None else "default"
says what was meant. The page runs both over "set", "", 0 and None so the divergence is visible rather than theoretical.
Where it belongs, and where it does not
A if-based formula is at its best when the two values are short, closely related, and the rule is easy to read. "pass" if score >= 50 else "fail" is a sentence. compute_full_report(user, opts) if user.is_active and not user.suspended else default_report() isn't, though it's legal and does the same kind of job.
The hands-on test is whether the line still reads left to right in one pass. If your eye has to go back to the middle to find the rule, or the line wraps, the statement form will be clearer and will cost you three extra lines that no one has ever regretted.
In default values and arguments
One place the formula form is truly the only option is inside another formula. Function args are the common case:
connect(host, timeout=timeout if timeout else DEFAULT_TIMEOUT)
and so are dict values, list elements and f-string slots. You can't put an if statement in any of those. If the choice has to happen there, this is how it happens.
Worth noticing in that example: timeout if timeout else DEFAULT has the same falsy-value problem as or. If zero is a legitimate timeout meaning "don't wait", this discards it. timeout if timeout isn't None else DEFAULT is the version that lives contact with real data.
Nesting, and the readable alternative
Chained if-based expressions are the classic overreach, and the reason is that they invert how people read a choice. A reader looking for the default case has to scan to the very end of the line. Adding a band means editing the middle of a long string of elses.
When the mapping is from ranges to values, a small loop over pairs often reads better than either the chain or a stack of ifs:
BANDS = [(90, "A"), (80, "B"), (70, "C")]
def grade(score):
for cutoff, letter in BANDS:
if score >= cutoff:
return letter
return "F"
The bands are now data. This Means they can be changed, tested and displayed without touching the logic. That is often the real win, and it's easy to miss while arguing about one-liners.
Seeing the or trap fail
The or shorthand and the clear if-based look the same until a falsy value goes through them:
def with_or(value):
return value or "default"
def with_cond(value):
return value if value is not None else "default"
for v in ["set", "", 0, None, False, []]:
print(repr(v), "->", repr(with_or(v)), repr(with_cond(v)))
'set' -> 'set' 'set'
'' -> 'default' ''
0 -> 'default' 0
None -> 'default' 'default'
False -> 'default' False
[] -> 'default' []
They agree on "set" and on None, and disagree on all else. or replaces the empty string, the zero, the False and the empty list — each one of which might be a legitimate value somebody on purpose supplied.
The cases where this matters are plain rather than exotic. A quantity of zero, an empty search box, a False flag the user really turned off, an empty list meaning "no tags". In each, or silently substitutes a default over the top of a real answer, and the bug reads as "my setting doesn't take effect".
or is still fine when each falsy value truly means "absent" — which is most often true for strings that are either a name or nothing. The discipline is to notice that you're making that claim rather than reaching for the shorter form by reflex.
It is an expression, and that is the whole distinction
All on this page follows from one fact: x if c else y makes a value, and if c: doesn't.
An formula can go wherever a value can. That is why it works inside an f-string, as a function arg, as a dict value, inside a comprehension and on the right of an set. A statement can go in none of those places, which is why the if-based formula isn't a shorter if — it's the only form that fits where a value is needed.
The converse is equally firm. An formula must give a value on each path, which is why the else is compulsory and why there's no one-armed version. It also can't hold statements: no set, no raise, no return inside it. If the branches need to *do* a thing rather than *be* a thing, the statement form is the only option.
This also shows the reading order. x if c else y puts the common case first because the whole thing is a value with a qualification attached, in the way English does — "the total, if there's one, or else zero". A statement starts with the question because it's about control flow, and control flow starts with a choice.
The walrus, and the other one-liner
A near neighbour worth distinguishing, because both compress a few lines into one and they do different things.
:=, the walrus operator, assigns *inside* an formula. So A value can be found and tested in one place: if (n := len(items)) > 10: binds n and checks it, and n is then available in the body without a second call. In a comprehension it's the way to avoid finding a thing twice: [y for x in data if (y := f(x)) isn't None] calls f once per item rather than once in the filter and again in the formula.
The gap from a if-based formula is clean. The walrus is about *naming* a value you're already finding. The if-based formula is about *choosing* between two values. They combine happily and neither replaces the other.
Both share a caution: they earn their place when they drop a genuine repetition or make a line fit where a statement can't. Used to compress code that was already clear, both make a reader stop, and neither is worth that.
Where you will actually meet it
Four places account for nearly each if-based formula in real code, and all four share the property that a statement couldn't go there.
Inside an f-string. f"{count} item{'s' if count != 1 else ''}" handles the plural without building the string in two steps. This is the single most common use, and it's worth having in your fingers.
As a default that depends on a thing. timeout=timeout if timeout isn't None else DEFAULT in an arg list, or as a dict value in a literal being made.
Inside a comprehension. Choosing what each item turns, not filtering which items appear — the gap covered elsewhere in the track.
**As a key= arg.** sorted(rows, key=lambda r: r.score if r.score isn't None else -1) puts missing values at one end without filtering them out first.
What none of these have in common with an if statement is that they're making a value in the middle of an formula that is already underway. That is the whole niche, and reaching for the form outside it. On a line of its own, assigning to a variable, when a plain if would do — is where it starts costing readability rather than saving it.
The if-based formula isn't a compressed if, and treating it as one makes the code that gives it a bad name. Three signals that the statement form is what you want.
The branches do a thing rather than give a thing. Logging, raising, assigning to more than one name, calling for a side effect. None of these fit in an formula, and contorting them to fit. A tuple of calls, an or chain with a function that raises. Makes code that is clever and unreadable in the same stroke.
There are more than two outcomes. A chain of elses pushes the default to the far end of the line and makes inserting a case an edit in the middle of a string of keywords. A sequence of if statements, or a table of thresholds, is both clearer and easier to change.
Either branch is long. Once the line wraps, the reader has to reassemble it across two lines to find where the rule sits. A four-line if costs three lines no one has ever regretted.
The version of the rule worth keeping: use the formula when you need a value *here*, in the middle of a thing else. Use the statement when you're deciding what the program does next.
Questions people ask about Conditional Expressions
Why is the rule in the middle? Because the formula is a value with a qualification, and putting the common case first makes it read as a sentence.
Can I leave out the else? No. An formula must give a value on each path.
Can I nest them? Legally yes, readably no past one level. A sequence of if statements or a table of bands is clearer.
Is it slower than an if statement? No, they compile to the same bytecode.
Can I use it on the left of an set? No. (a if c else b) = 1 isn't valid. Only names and subscripts can be assigned to.
What is Python's version of the ternary ?:? This is it. Python spells it with words rather than punctuation, on purpose.
Can I put a raise in one? No, raise is a statement. There's an idiom using or with a function that raises, and it's worse than writing the if.
Does it short-circuit? Yes. Only the branch that is chosen is tested, so the other side can safely be a thing that would fail.
Can I use it with and/or in the rule? Yes, and brackets are worth adding when you do. The precedence is correct but not obvious to a reader.
Does it work in a lambda? Yes, and it's one of the few ways to get a choice into one, since a lambda body must be a single formula.
Is there a null-coalescing operator like ??? No. The clear x if x isn't None else y is Python's version, and its verbosity is deliberate — it makes you say which falsy values you meant.
Can the two branches return different types? Yes, nothing stops you. Whether the caller can cope with either is a separate question, and often the answer is that it shouldn't have to.
Conditional Expressions: recap in one screen
value_if_true if rule else value_if_false — the value first, the rule second.- It's an formula, so it fits inside f-strings, comprehensions and arg lists where a statement can't.
- The
else is compulsory, because an formula must always give a thing. x or default replaces each falsy value, not just None. Use the clear isn't None form when zero or empty is legitimate.- One rule and short values on one line. Past that, write the statement or put the bands in a list.