8

我对分配为 False、True 的测试值有些困惑

要检查 True 值,我们可以简单地

a = True
if (a):

假的怎么样?

a=False
if (a) <--- or should it be if (a==False), or if not a ?
4

3 回答 3

29

来自Python 风格指南

对于序列(字符串、列表、元组),使用空序列为假的事实。

Yes: if not seq:
     if seq:

No: if len(seq)
    if not len(seq)

[..]

不要使用 == 将布尔值与 True 或 False 进行比较。

Yes: if greeting:
No: if greeting == True:
Worse: if greeting is True:
于 2013-09-11T16:02:20.803 回答
6

使用not

if not a:
    ....
    # If a is the empty value like '', [], (), {}, or 0, 0.0, ..., False
    # control flow also reach here.

is False

if a is False:
    ....
于 2013-09-11T15:57:08.410 回答
1

要检查一个值是否为真:

if a:
    pass

要检查一个值是否不正确:

if not a:
    pass

但是,对于 以外的值not a:True(并且为真)False,例如。None, 0, 和空容器。

如果你想检查一个值是否是TrueFalse(虽然你通常不)尝试:

if a is True:
    pass

或者

if a is False:
    pass

编辑:用于检查一个值是否是 True或者False看起来你应该使用if isinstance(a, bool) and a, 和if isinstance(a, bool) and not a

于 2013-09-11T16:00:58.753 回答