Skip to content

conditional expression

In Python, a conditional expression chooses between two values based on a condition, written as x if condition else y. Python evaluates the condition first, even though x comes first in the source. When the condition is truthy, the whole expression evaluates to x, and when it’s falsy, it evaluates to y. Only the branch you land on runs, so the other one never gets the chance to raise an exception.

Because it’s an expression rather than a statement, it produces a value and fits anywhere a value belongs. You can drop one into a comprehension, an argument list, or an f-string replacement field, none of which accept an if block. You’ll also see it called the ternary operator, after the three operands it takes, and PEP 308 settled on the current spelling for Python 2.5.

Conditional expressions sit near the bottom of the operator precedence table, above only lambda and the assignment expression operator (:=). Binding that loosely means the expression claims as much of its surroundings as it can, so parenthesize it when you nest it inside something larger. Chaining several in a row is legal and groups from right to left, though a chain usually reads worse than the if statement it replaced.

Toggle the parentheses below to watch how much of the surrounding expression the if claims, and what that changes when the condition is falsy:

Interactive diagram — enable JavaScript to view.

Example

Say you’re working out each player’s hit rate for a scoreboard, and a player who hasn’t taken a shot yet would divide by zero:

Language: Python
>>> attempts = {"ana": 20, "bo": 0, "cy": 15}
>>> hits = {"ana": 9, "bo": 0, "cy": 12}

>>> {name: hits[name] / n if n else 0.0 for name, n in attempts.items()}
{'ana': 0.45, 'bo': 0.0, 'cy': 0.8}

The conditional expression fills the value slot of a dict comprehension, where a statement isn’t allowed. For "bo", the condition n is falsy, so Python skips the division and hands back 0.0 instead of raising ZeroDivisionError.

Conditional Statements in Python

Tutorial

Conditional Statements in Python

In this step-by-step tutorial you'll learn how to work with conditional ("if") statements in Python. Master if-statements and see how to write complex decision making code in your programs.

basics python

For additional information on related topics, take a look at the following resources:

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Martin Breuss • Updated Oct. 4, 2026