1

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.

5
  • You can nest ternary, yes, but why? Commented Jun 2, 2017 at 1:48
  • 2
    'a' if 1 == 2 else 'b' if 2 == 3 else 'c' Commented Jun 2, 2017 at 1:49
  • 1
    Sort of. You can nest ternary statements. But once you get to that point, I think that readability outweighs convenience and I'd just use a regular if statement. Commented Jun 2, 2017 at 1:50
  • As you wrote yourself, it is a ternary operator, having three operands. An elif would introduce two more. Commented Jun 2, 2017 at 2:47
  • @KlausD. Ok, thanks. Commented Jun 2, 2017 at 2:50

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

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!

7 Comments

What is test1() and test2()?
any function or expression that returns a True or False value.
@EnderLook: They are just examples. You could replace them with your tests; e.g. a == b or e == f.
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.
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.
|
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.