Python布尔变量,True、False和None

Python布尔变量,True、False和None,python,Python,我有一个名为映射的布尔变量\u filter。 如果我没有错,这个变量可以包含3个值,要么True,False,要么None 我想区分if语句中的3个可能值。有没有比做以下事情更好的方法 if mapped_filter: print("True") elif mapped_filter == False: print("False") else: print("None") 在您的代码中,任何不真实或False的内容都会打印“无”,即使是其他内容。因此,[]将打印无。

我有一个名为
映射的布尔变量\u filter
。 如果我没有错,这个变量可以包含3个值,要么
True
False
,要么
None

我想区分
if
语句中的3个可能值。有没有比做以下事情更好的方法

if mapped_filter:
    print("True")
elif mapped_filter == False:
    print("False")
else:
    print("None")

在您的代码中,任何不真实或
False
的内容都会打印
“无”
,即使是其他内容。因此,
[]
将打印
。如果除了
True
False
None
之外没有其他对象可以到达那里,那么您的代码就可以了

但在python中,我们通常允许任何对象真实与否。如果您想这样做,更好的方法是:

if mapped_filter is None:
    # None stuff
elif mapped_filter:
    # truthy stuff
else:
    # falsey stuff
如果明确不允许任何非
bool
None
的值,请执行以下操作:

if isinstance(mapped_filter, bool):
    if mapped_filter:
        # true stuff
    else:
        # false stuff
elif mapped_filter is None:
    # None stuff
else:
    raise TypeError(f'mapped_filter should be None or a bool, not {mapped_filter.__class__.__name__}')

如果mapped\u filter为None
则与
None
相比无误。如果您要查找
案例
语句,很抱歉,但是没有更好的方法。你仍然可以做一些疯狂的事情,比如拥有一本字典,比如
疯狂字典={True:…,False:…,None:…}
然后
疯狂字典[映射过滤器]()
。你的假设是错误的。如果
mapped\u filter
是一个布尔值,它只能有两个不同的值:
True
False
。这就是我想要的。这种方法看起来更好。谢谢