Ternary Conditional Operator in Python
The ternary conditional operator is an easier way of writing an if-else statement. The ternary operator has three components: expression, positive value and negative value.
In the standardized way of expressing the ternary operator, we use a question mark and a colon.
Syntax :
expression ? positive value : negative value
When the expression evaluates to true, the positive value is used—otherwise, the negative value is used.
eligible_for_voting = (age >= 18) true : false; # standardized ternary operator
Python on the other hand does not use the above-standardized syntax. In Python, the components are rearranged and the keywords if and else are used.
Syntax :
[positive value] if [expression] else [negative value]
Ternary Operators, also called as conditional expressions, are operators that evaluate something based on a condition being true or false. These have the lowest priority of all Python operators.
The first condition gets evaluated, then based on the Boolean value of the condition, either a or b is returned.
If the condition returns True, a is returned, else b is returned.
Example 1:
>>eligible_for_voting = True if age >= 18 else False #Python Ternary Operator
Example 2:
>>a = 10 >>b = 20 >>c = 2 * a if a == 10 else b
Output:
20