📅 2012-Apr-24 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ conditional expression, python, ternary operator ⬩ 📚 Archive
Python does not have the ternary operator seen in C-like languages. Instead it has the conditional expression. It is of the form X if C else Y
:
= 99
i = True if 99 == i else False
x # True
In X if C else Y
, either or both of X and Y can themselves be conditional expressions:
= 99
i = 42
j = ( list() if 42 == j else tuple() ) if 99 == i else False
x # []
The conditional expression can be used as a cool and easy-to-read alternative to a chain of if-else statements:
# Peter Norvig's example in Udacity CS212
return (
9 if (5, ) == counts else
8 if straight and flush else
7 if (4, 1) == counts else
6 if (3, 2) == counts else
5 if flush else
4 if straight else
3 if (3, 1, 1) == counts else
2 if (2, 2, 1) == counts else
1 if (2, 1, 1, 1) == counts else
0)
For more info on conditional expressions, see Expressions and PEP 308.
Tried with: Python 3.2.2