Python Conditional Expression is also called Ternary Operator. It is an alternative to a simple Python if else statement.
Syntax of Python Ternary Operator or Conditional Expressions
x if C else y
Where x is a simple Python expression or statement. The C represents a given condition. The y represents another simple Python expression or statement.
More clear syntax will be:
expression1 if condition else expression2
Working of Python Ternary Operator or Conditional Expressions
First of all the given condition C is evaluated. If it is ture then x is evaluated and its value returned. On the other hand, if the given condition is false, then y is evaluated and its value is returned.
First Example of Ternary Operator
or Conditional Expressions
n=10 is_even = True if n%2==0 else False print(is_even)
The output of the above Python conditional expression
will be:
True
Second Example of Conditional Expressions
grade=17 basic_pay=10000 house_rent=basic_pay*5/100 if grade<17 else basic_pay*10/100 print('House Rent=',house_rent)
This Python script for using Ternay operator will give the following output:
House Rent= 1000.0
Third Example of Ternary Operator in Python
n=10 print('even') if n%2==0 else print('odd')
The output will be as follows:
even
Since the condition is true, therefore the first expression is returned.