Ternary operators also referred to as conditional expressions are operators that evaluate something supported a condition being true or false. it had been added to Python in version 2.5.
It simply allows to check a condition during a single line replacing the multi line if-else making the code compact.
[on_true] if [expression] else [on_false]
1.Simple Method to use ternary operator:
2.Direct Method by using tuples, Dictionary and lambda
3.Ternary operator can be written as nested if-else:
- First the given condition is evaluated (a < b), then either a or b is returned supported the Boolean value returned by the condition
- Order of the arguments within the operator is different from other languages like C/C++ (See C/C++ ternary operators).
- Conditional expressions have rock bottom priority among set all Python operations.
Method used prior to 2.5 when ternary operator was not present:
In an expression just like the one given below, the interpreter checks for the expression if this is often true then on_true is evaluated, else the on_false is evaluated.