为什么不是True == True:

Pet*_*ore 5 python

样式指南的最后一点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)

隐式转换掩盖了逻辑错误.那么为什么风格指南鼓励这个呢?

Mar*_*ers 7

这意味着你应该写

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)

额外的测试是多余的,不会为代码添加任何值,因此应删除它们.

  • 令人惊讶的是人们如何得不到布尔.例如"bool Predicate(){if(condition)return true; else return false;}" - 什么?这可以简单地写成"bool Predicate(){return condition;}"! (3认同)
  • @mgibsonbr你可以使用`bool`将值强制为布尔值. (2认同)