Python Ternary Operators: Explained With Example
What are Ternary Operators in Python?
Conditional expressions, often known as ternary operators, are operators that evaluate something dependent on whether a condition is true or false.
It was added for the first time in Python 2.5. To test a condition, it simply substitutes the multiline if-else with a single line, making the code more compact.
Operands of Ternary Operator in Python
The ternary operator in Python has three operands:
1. conditional_expression: It evaluates to either true or false.
2. true_value: If the conditional expression evaluates to True, the ternary operator returns this value.
3. false_value: If the conditional expression evaluates to False, the ternary operator returns this value.
Conditional expression is a boolean value
not_raining = False print("Go for a run" if not_raining else "watch Netflix")
not_raining = True print("Go for a run" if not_raining else "watch Netflix")