风格指南的最后一点http://www.python.org/dev/peps/pep-0008
读...
不要使用 == 将布尔值与 True 或 False 进行比较。
为什么?
编辑只是为了弄清楚我在问什么(这表明问题本身),当你写的时候
if something:
print "something is true"
您正在对布尔值进行隐式转换,这可能会或可能不会起作用,具体取决于 true 的含义。恕我直言,不鼓励这种形式的编程,因为它可能导致副作用。
numberOfApples = -1
if numberOfApples:
print "you have apples" # is not what is intended.
if numberOfApples == True:
print "you have apples" # is also not what is intended.
iHaveApples = numberOfApples > 0
if iHaveApples is True: # Edit: corrected this.. the "is" is better than the ==
print "you have apples" # is correct.
隐式转换掩盖了逻辑错误。那么为什么风格指南鼓励这样做呢?