Python ternary operator [duplicate]
Asked Answered
E

2

64

How can I do something like var foo = (test) ? "True" : "False"; in Python (specifically 2.7)?

Escarp answered 5/11, 2010 at 4:51 Comment(0)
C
94

PEP 308 adds a ternary operator:

foo = "True" if test else "False"

It's been implemented since Python 2.5

Cedrickceevah answered 5/11, 2010 at 4:52 Comment(2)
Wow. You beat me by 12 seconds and have character for character the same answer I did.Rollicking
Thanks, I will accept this answer as soon as SO allows it :)Escarp
P
-1

This one looks a bit more like original ternary:

foo=a and b or c
Pentahedron answered 5/11, 2010 at 9:24 Comment(2)
f = a or b or c works the same as in javascript (it returns the first truthy value).Infuse
-1 Beware, there is a case where this does not work: if the condition a is True and b is any false value, such as False, 0, None, [], {} and so on, then the result is c, which is wrong (it should be b). For example, (True and [] or [1,2,3]) is equal to [1,2,3], while ([] if True else [1, 2, 3]) is equal to [], as it should be. I recommend sticking to the official ternary operator.Homemaking

© 2022 - 2024 — McMap. All rights reserved.