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

时间:2015-01-02 16:43:44

标签: python

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

if True:
    pass

if (True):
    pass

这些之间是否有任何差异,甚至性能差异?

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

如编译的字节代码所示,

>>> 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. 如果要对条件进行逻辑分组,可能需要使用parens。例如,

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

    看起来会更好

    if (10/5 == 2) and (2*5 == 10):
        pass
    
  2. 你可以尽可能避免使用parens来使条件更像英语句子。

答案 2 :(得分:1)

与大多数语言一样,会忽略额外的括号。在Python中,if语句根本不需要任何语句。两个陈述都是相同的。

答案 3 :(得分:0)

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

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

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: