Python布尔真值测试

SK9*_*SK9 4 python boolean

可能重复:
Python三元运算符

Python有相同的ternary运算符吗?:

( x < 5 ? 1 : 0 )
Run Code Online (Sandbox Code Playgroud)

或者我必须用一if-else对表达相同的东西?

Gre*_*ill 12

您可以使用条件表达式:

1 if x < 5 else 0
Run Code Online (Sandbox Code Playgroud)

在为非常旧版本的Python编写的代码中,您可能还会看到:

x < 5 and 1 or 0
Run Code Online (Sandbox Code Playgroud)

但是,对于Python 2.5及更高版本,首选条件表达式.

  • 当然,在这种特殊情况下,您可以使用`x <5`作为值本身,或者`bool(x <5)`如果`x`是一种特别奇怪的类型. (2认同)