0

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.

Ender Look
  • 1,954
  • 2
  • 16
  • 32

3 Answers3

5

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."

ShadowRanger
  • 108,619
  • 9
  • 124
  • 184
3
'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!

Tasos Papastylianou
  • 18,605
  • 2
  • 20
  • 44
  • What is `test1()` and `test2()`? – Ender Look Jun 02 '17 at 01:53
  • any function or expression that returns a True or False value. – Tasos Papastylianou Jun 02 '17 at 01:54
  • 2
    @EnderLook: They are just examples. You could replace them with your tests; e.g. `a == b` or `e == f`. – zondo Jun 02 '17 at 01:54
  • 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 Jun 02 '17 at 01:56
  • 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_. – Tasos Papastylianou Jun 02 '17 at 01:59
2

You can nest ternaries:

a = b if c == d else (i if e == f else j)

I can't think of any language that has a ternary operator with an elseif syntax. The name "ternary" means there are just 3 parts to the operator: condition, then, and else.

Barmar
  • 596,455
  • 48
  • 393
  • 495