我正在使用表现出以下行为的代码。假设我有一个变量 d
并将其分配给一个整数 9
d = 9
为什么下面的语句有效?
In [95]: if d:
....: print d
....: else:
....: print 'Did not print d!'
....:
9
In [96]:
当 d 本身不是 boolean 值且未通过以下测试时:
In [96]: d is True
Out[96]: False
In [97]: d is False
Out[97]: False
如果有人能向我解释这一点并指出我的任何误解,我将不胜感激。非常感谢。
最佳答案
引自official Python documentation ,
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false:
False
,None
, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.
if
语句属于Booelan 操作的上下文。由于 d
为 9
不属于任何错误值,因此它被视为 Truthy。
你可以这样确认
>>> all(bool(value) is False for value in (False, 0, +0, -0, "", (), [], {}, set()))
True
虽然值 9
既不是 True
也不是 False
,你用 d 确定是 True
和 d is False
测试,由于上述原因,它被认为是 Truthy。
>>> bool(9)
True
关于python - 不明白为什么当变量为整数时 if 条件的计算结果为 True,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27853301/