Skip to main content

The Ternary Operator

The ternary operator assigns one value when a condition holds and another when it doesn't.

Note: Despite the name, it isn't really an operator. It is a conditional expression, a shorthand form of the if statement.

Example

Store "WEEKEND!" when the number is above 5, and "Workday" in every other case:

Prompt
Write a Python program that assigns num = 6, then uses the ternary operator to assign "WEEKEND!" to x if num > 5, otherwise "Workday", and prints x.
Output: complete Python program

Instead of Elif

A long if statement with several elif branches can also be replaced by ternary operators:

Example

Give x the value "Fri" when num is 5, "Sat" when it is 6, "Sun" when it is 7, and "weekday" for anything else:

Prompt
Write a Python program that assigns num = 6, then uses chained ternary operators to assign "Fri" if num == 5, "Sat" if num == 6, "Sun" if num == 7, otherwise "weekday", and prints x.
Output: complete Python program