if语句中有括号和没有括号的区别

Difference between having and not having parenthesis in if statements

在python中,if语句可以带括号也可以不带括号:

if True:
    pass

if (True):
    pass

它们之间有任何区别,甚至是性能差异吗?

在Python中,不需要括号。您通常使用它们来对较长的复杂表达式进行分组。

与大多数语言一样,多余的括号会被忽略。在 Python 中,if 语句根本不需要任何内容​​。两种说法完全相同。

如编译后的字节码所示,

>>> from dis import dis
>>> dis(compile("if True: pass", "string", "exec"))
  1           0 LOAD_NAME                0 (True)
              3 POP_JUMP_IF_FALSE        9
              6 JUMP_FORWARD             0 (to 9)
        >>    9 LOAD_CONST               0 (None)
             12 RETURN_VALUE        
>>> dis(compile("if (True): pass", "string", "exec"))
  1           0 LOAD_NAME                0 (True)
              3 POP_JUMP_IF_FALSE        9
              6 JUMP_FORWARD             0 (to 9)
        >>    9 LOAD_CONST               0 (None)
             12 RETURN_VALUE        

它们之间完全没有区别。我能想到的有两件事。

  1. 当您想要对条件进行逻辑分组时,您可能需要使用括号。例如,

    if 10/5 == 2 and 2*5 == 10:
        pass
    

    看起来会更好

    if (10/5 == 2) and (2*5 == 10):
        pass
    
  2. 您可以通过尽可能避免括号来使条件更像英语句子。

要记住的另一件事是对条件进行分组。

在括号中包含条件可以稍微改变预期的顺序:

x = True
y = True
z = True

if x==False and y==False or z==True:
    print 'foo'  # This will print

if x==False and (y==False or z==True):
    print 'bar'  # This will not print

第一条语句应读作if (x==False and y==False) or z==True: