Conditional Expressions in Python
In Python conditional expression are sometimes referred to operator called as ternary operator. Not only Python supports ternary operator but many other programming languages supports it. Ternary operator are the operators that execute and solve the code based on Boolean expression i.e., true (or) false.The ternary operator was not present in the Python libraries when it was introduced, it was introduced to Python libraries from 2.5 version. The ternary operator is used to deploy the code in just one line rather than writing the whole block of if-else making the code long and complex. It totally works on the Boolean conditions.
Note: Ternary operator is simple a one line of code based on expressions.
Ternary operator consists of 3 operands in it and it follows as:
- CONDITION EXPRESSION
Its syntax follows:
[VALUE1] if [EXPRESSION] else [VALUE2]
This is also referred as true value because the true expression is validated in this block and if it is true, it is executed, and output expected.
This is also referred as false value because the false expression is validated in this block and if it is false, it is executed, and output is displayed according to the code.
It is sandwiched between the true and false expression as it is the one who performs execution and process the code. And it can contain statements like if and else.
And the syntax is slightly modified with the variable declared to its left by using the assignment operator.
# PROGRAM TO CHECK A NUMBER EVEN OR ODD A = 4 ANS = ‘Even’ if A % 2 == 0 else ‘Odd’ print (ANS)
#PROGRAM TO COMPARE TWO NUMBERS AND FINDING THE LARGEST NUMBER A = 8 B = 9 print (“A” if A > B else “B”)