bhylu.com

Advertisements

Ternary Operator

A conditional expression chooses one of two values inline. It is handy for a short label, while a full if statement is better when each branch performs several steps.

Understand the idea

The form is value_if_true if condition else value_if_false. Only the selected value expression is evaluated. Keep the branches short enough that the condition is obvious without rereading it. Several nested conditional expressions usually make a simple rule harder to test and maintain.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

stock = 0
label = "Available" if stock > 0 else "Sold out"
print(label)

Read the result

The output is Sold out because the condition is false. The expression produces one string value for label.

Try one change

Change stock to 4 and then rewrite the expression as an ordinary if/else block to compare readability.