【问题标题】:Why is the purpose of the "else" clause following a "for" or "while" loop? [duplicate]为什么“else”子句的目的是在“for”或“while”循环之后? [复制]
【发布时间】:2012-07-19 07:20:44
【问题描述】:

我是 Python 初学者。我发现for-elsewhile-else 中的else 是完全没有必要的。因为forwhile 最终会运行到else,我们可以使用通常的行来代替。

例如:

for i in range(1, 5):
    print i
else:
    print 'over'

for i in range(1, 5):
    print i
print 'over'

都是一样的。

那么为什么 Python 在for-elsewhile-else 中有else

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    你对 for/else 的语义有误。 else 子句仅在循环完成时运行,例如,如果没有遇到 break 语句。

    典型的 for/else 循环如下所示:

    for x in seq:
        if cond(x):
            break
    else:
        print "Didn't find an x I liked!"
    

    将“else”视为与循环体中的所有“if”配对。您的示例是相同的,但混合了“break”语句,它们不是。

    同一想法的详细描述:http://nedbatchelder.com/blog/201110/forelse.html

    【讨论】:

      【解决方案2】:

      for ... else 语句用于实现搜索循环。

      特别是,它处理搜索循环找不到任何东西的情况。

      for z in xrange(10):
          if z == 5:
              # We found what we are looking for
              print "we found 5"
              break # The else statement will not execute because of the break
      else:
      
          # We failed to find what we were looking for
          print "we failed to find 5"
          z = None
      
      print 'z = ', z
      

      输出:

      we found 5
      z =  5
      

      那个搜索是一样的

      z = None
      for z in xrange(10):
          if 5 == z:
              # We found what we are looking for
              break
      
      if z == None:
          print "we failed to find 5"
      else:
          print "we found 5"
      
      print 'z = ', z
      

      请记住,如果搜索列表为空(即[]),for 不会初始化 z。这就是为什么我们必须确保在搜索后使用 z 时定义它。以下将引发异常,因为在我们尝试打印时未定义 z

      for z in []:
          if 5 == z:
              break
      
      print "z = ",z
      

      输出

          print "z = ",z
      NameError: name 'z' is not defined
      

      总之,只要for 循环自然终止,else 子句就会执行。如果for 循环中出现中断或异常,else 语句将不会执行。

      【讨论】:

        猜你喜欢
        • 2012-04-16
        • 2014-06-30
        • 2011-04-21
        • 2016-05-27
        • 2015-05-30
        • 1970-01-01
        • 2020-06-11
        相关资源
        最近更新 更多