I am learning python using the excellent book by Mark Lutz. I come across this statement that the ternary operator in python, which is effectively this:
if a:
b
else:
c
can be written in 2 ways:
b if a else c: using normal ternary syntax of python and((a and b) or c): using the equivalent but trickierand/orcombination
I find the second representation disconcerting as it doesn't go well with my instinct. I tried these 2 syntax on the interactive prompt and found different answers for special case of b = 0. (assume b = 0, a = 4, c = 20)
0 if 4 else 20outputs0((4 and 0) or 20)outputs20
It appears that the 2 expressions are equivalents for all the truthy values of b but are not equivalent for all the falsy values of b.
I want to know, is there anything that I am missing here. Is my analysis wrong? Why does it say so in the book that the two cases are equivalent. Please enlighten my coarse mind. I am new to python. Thanks in advance.
[c, b][bool(a)], and ifais a boolean expression, you can omit thebool[c,b][bool(a)]sounds cool and innovative. does it also fail for any such special cases? I hope not.