4.7 Conditional expressions
Learning objectives
By the end of this section you should be able to
- Identify the components of a conditional expression.
- Create a conditional expression.
Conditional expressions
A conditional expression (also known as a "ternary operator") is a simplified, single-line version of an if-else statement.
Conditional expression template:
expression_if_true if condition else expression_if_false
A conditional expression is evaluated by first checking the condition. If condition is true, expression_if_true is evaluated, and the result is the resulting value of the conditional expression. Else, expression_if_false is evaluated, and the result is the resulting value of the conditional expression.
A variable can be assigned with a conditional expression. Ex: Finding the max of two numbers can be calculated with max_num = y if x < y else x
Note: Conditional expressions have the lowest precedence of all Python operations.