Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Operator x if condition else y

Selects one of two expressions according to a truth test.

Version: Python 3.14; repository image, production runtime not attested

Syntax

x if condition else y

Selects one of two expressions according to a truth test.

The condition is evaluated first even though it appears in the middle. A true condition selects the expression on the left and a false condition selects the expression on the right.

Use a conditional expression to choose the value being assigned. Each branch can yield a different type, and an exception in the condition propagates before either branch runs.

Only the selected expression is evaluated, so a failing expression in the other branch is skipped.

Syntax

x if condition else y

chosen if condition else other

Worked example

4 if True else 1 / 0 → 4
4 if False else 8 → 8

Examples

print(12 if 3 > 0 else 0)
print(6 if True else 1 / 0)

Result

12
6

Only the selected expression is evaluated, so a failing expression in the other branch is skipped.

Sources