Use Python’s conditional expression

Choose between two values with value_if_true if condition else value_if_false, and keep false values distinct from missing values.

Best practices
Python programming and application logging

Python's conditional expression is value_if_true if condition else value_if_false. Use it when a short expression needs to choose one of two values.

age = 20
status = "adult" if age >= 18 else "minor"

The equivalent statement is:

if age >= 18:
    status = "adult"
else:
    status = "minor"

Python evaluates the condition first, then only the selected value expression. An unselected branch is not evaluated.

Common uses

x = -7
abs_value = x if x >= 0 else -x

score = 75
print(f"Result: {'pass' if score >= 60 else 'fail'}")

def parity(number):
    return "even" if number % 2 == 0 else "odd"

For a user object that may be absent, an explicit test distinguishes absence from other false-like objects:

name = user.name if user is not None else "Anonymous"

Here user must already be defined, and a present object must expose name. Use if user only when all false values are intended to select the fallback.

Keep branching readable

An expression such as "A" if score > 90 else "B" if score > 80 else "C" is legal, but repeated nesting becomes harder to scan. Use if/elif/else when branches contain substantial logic or several conditions deserve names. Conditional expressions are for choosing a value, not for compressing every statement into one line.

FAQ

Can I leave out else? No. The conditional expression needs a value for either outcome. A comprehension's trailing if is a separate filtering syntax.

Is value or fallback equivalent? Only when you want the fallback for every false value. 0, "", empty containers, and None all trigger or. To substitute only for a missing value, use value if value is not None else fallback.

Does the shorter form run faster? There is no useful general speed guarantee. Prefer the form that makes the decision clear, and benchmark only if it is part of a measured bottleneck.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting