我的交互式控制台中的简要记录:
Python 2.7.2 (default, Jun 29 2011, 11:10:00)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> True
True
>>> 0 == True
False
>>> 1 == True
True
>>> 2 == True
False
为什么会出现这种情况?
编辑:为了对比,请考虑is
运算符。
>>> 0 is False
False
>>> 1 is True
False
>>> 0 is 0
True
>>> True is True
True
这很有道理,因为尽管1
和True
在if
语句的条件中具有相同的含义,但它们并不是完全相同的东西。
再次编辑:1 == True
还有更多有趣的结果:
>>> d = {}
>>> d[True] = "hello"
>>> d[1]
"hello"
2 != True
。 - MchlTrue=-1
,False的标识为False=0
。如果你在VB中测试True=+2
、True=1
、False=0.4575
或False=-999
,它们都会返回false。在Python中:同样的思路,具体细节不同。2 != True
并不神秘。 - Jean-François Corbettd[1] is d[True]
的部分是出乎意料的... - Armando Pérez Marqués