标签云

微信群

扫码加入我们

WeChat QR Code

Possible Duplicate:Ternary conditional operator in Pythonvar foo = (test) ? "True" : "False";What would this look like in Python?Using Python 2.7 if that makes a difference.


Wow. You beat me by 12 seconds and have character for character the same answer I did.

2019年06月19日06分03秒

Thanks, I will accept this answer as soon as SO allows it :)

2019年06月19日06分03秒

f = a or b or c works the same as in javascript (it returns the first truthy value).

2019年06月19日06分03秒

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

2019年06月19日06分03秒