Ternary Operator in Python
The python ternary operator is very simple and easy to use.
Syntax:
|
1 |
a if test else b |
Example 1:
|
1 2 |
a = 2 print 2 if a ==2 else 4 |
Output :
2
Example 2:
|
1 2 |
a = 4 print 2 if a ==2 else "not equal to 2" |
output:
not equal to 2