Python 将 0 评估为 False
问题描述
在 Python 控制台中:
In the Python console:
>>> a = 0
>>> if a:
... print "L"
...
>>> a = 1
>>> if a:
... print "L"
...
L
>>> a = 2
>>> if a:
... print "L"
...
L
为什么会这样?
解决方案
在Python中,bool
是int
的子类,False
值为 0
;即使值没有在 if
语句(它们是)中隐式转换为 bool
,False == 0
也是 true.
In Python, bool
is a subclass of int
, and False
has the value 0
; even if values weren't implicitly cast to bool
in an if
statement (which they are), False == 0
is true.
相关文章