1

Sometimes I want to check the logical value of an expression, so I type it in Python (or IPython) and get the result:

>>> a==3
True

But in other cases it doesn't work that way (here string is None):

>>> string
>>>

So I check the logical value like this:

>>> if string: print('True')
...
>>>

Is there a shorter way for checking the logical value of an expression? Any function that returns True or False the same way it will be evaluated in an if-condition?

4

4 回答 4

7

除了产生None的表达式之外的所有表达式都被回显。

如果您执行的表达式不会导致数据被回显,那么您可能会得到None结果。您可以None明确测试:

>>> string = None
>>> string is None
True

使用is None会产生非None结果。

如果您只想测试表达式的布尔值,请使用bool()函数;它将按照标准真值测试规则返回结果:

>>> string = None
>>> bool(string)
False

同样,这保证不会被None呼应。但是,您无法通过这种方式区分None和其他 false-y 值。例如,空字符串''也会导致False.

另一种选择是使用以下repr()函数显式打印所有表达式结果:

>>> print(repr(string))
None

然后,这会产生与回显完全相同的输出,但None也会打印一个异常。

于 2017-09-15T09:05:19.163 回答
5

有没有更短的方法来检查表达式的逻辑值?

是的,它的bool()功能:

>>> string = None
>>> bool(string)
False
于 2017-09-15T09:05:46.370 回答
2

是的,直接从表达式创建一个布尔值,它始终是Trueor False

>>> bool(string)
False
于 2017-09-15T09:06:34.400 回答
1

string is Nonestring is not None将返回您需要的布尔值。

>>> string = None
>>> string is None
>>> True
于 2017-09-15T09:06:45.107 回答