I have recently found this question: Does Python have a ternary conditional operator? and discover something called ternary conditional a = b if c == d else e.
My question: There is a way to make ternary conditional with elif? something like a = b if c == d elif e == f i else j.
3 Answers
You can chain the conditional operator, but it's not recommended, since it gets pretty hard to read. The associativity works the way you expect (like every language aside from PHP):
a = b if c == d else i if e == f else j which means in English "assign b to a if c equals d, otherwise, assign i if e equals f, and j if not."
Comments
'Yes' if test1() else 'Maybe' if test2() else 'No' PS. Also, be careful, you probably meant a==b which is checking for equality, rather than a=b which is assignment!
7 Comments
Ender Look
What is
test1() and test2()?Tasos Papastylianou
any function or expression that returns a True or False value.
zondo
@EnderLook: They are just examples. You could replace them with your tests; e.g.
a == b or e == f.Tasos Papastylianou
yes, as zondo said. In general, unless your test is very simple (like a==b), it's best to prefer appropriately named, readable functions to make your code read like English.
Tasos Papastylianou
Also, it's important to realise the difference between the 'ternary operator' (i.e.
return_value1 if test1 else return_value2 if test2 else return_value3) and a normal if ... else block, which performs actions depending on the tests, but doesn't return anything per se. |
'a' if 1 == 2 else 'b' if 2 == 3 else 'c'elifwould introduce two more.