样式指南的最后一点http://www.python.org/dev/peps/pep-0008
读......
不要使用==将布尔值与True或False进行比较.
为什么?
编辑只是为了清楚地说明我在问什么(并且它表明了问题本身),当你写作时
if something:
print "something is true"
Run Code Online (Sandbox Code Playgroud)
您正在进行一个隐式转换为布尔值,这可能会或可能不会取决于真正的含义.恕我直言,这种形式的编程是不鼓励的,因为它可能导致副作用.
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.
Run Code Online (Sandbox Code Playgroud)
隐式转换掩盖了逻辑错误.那么为什么风格指南鼓励这个呢?
这意味着你应该写
if greeting:
Run Code Online (Sandbox Code Playgroud)
代替:
if greeting == True:
Run Code Online (Sandbox Code Playgroud)
同样,你不应该写这个:
if (greeting == True) == True:
Run Code Online (Sandbox Code Playgroud)
额外的测试是多余的,不会为代码添加任何值,因此应删除它们.