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
.
Asked
Active
Viewed 4,192 times
0

Ender Look
- 2,303
- 2
- 17
- 41
-
You can nest ternary, yes, but why? – OneCricketeer Jun 02 '17 at 01:48
-
2`'a' if 1 == 2 else 'b' if 2 == 3 else 'c'` – blacksite Jun 02 '17 at 01:49
-
1Sort 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. – Christian Dean Jun 02 '17 at 01:50
-
As you wrote yourself, it is a ternary operator, having three operands. An `elif` would introduce two more. – Klaus D. Jun 02 '17 at 02:47
-
@KlausD. Ok, thanks. – Ender Look Jun 02 '17 at 02:50
3 Answers
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
- 143,180
- 12
- 188
- 271
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
- 21,371
- 2
- 28
- 57
-
-
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
- 741,623
- 53
- 500
- 612