开发者

Python boolean truth tests [duplicate]

开发者 https://www.devze.com 2023-03-13 12:44 出处:网络
This question already has answers here: Closed 10 years ago. 开发者_JS百科Possible Duplicate: Python Ternary Operator
This question already has answers here: Closed 10 years ago.
开发者_JS百科

Possible Duplicate:

Python Ternary Operator

Does Python have an equivalent of the ternary operator?:

( x < 5 ? 1 : 0 )

Or must I express the same thing with an if-else pair?


You can use a conditional expression:

1 if x < 5 else 0

In code written for very old versions of Python, you may also see:

x < 5 and 1 or 0

However, the conditional expression form is preferred for Python 2.5 and later.


Python has:

1 if x < 5 else 0

or the old style:

x < 5 and 1 or 0
0

精彩评论

暂无评论...
验证码 换一张
取 消