Python while 语句中的 Else 子句

新手上路,请多包涵

我注意到以下代码在 Python 中是合法的。我的问题是为什么?有具体原因吗?

 n = 5
while n != 0:
    print n
    n -= 1
else:
    print "what the..."


Many beginners accidentally stumble on this syntax when they try to put an if / else block inside of a while or for loop, and不要正确缩进 else 。解决方案是确保 else 块与 if ,假设您打算将它们配对。这个问题解释了 _为什么它没有导致语法错误_,以及 结果代码的含义。 另请参阅 我收到 IndentationError。我如何解决它? ,对于报告语法错误的 _情况_。

原文由 Ivan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 236
1 个回答

else 子句仅在您的 while 条件变为假时执行。如果你 break 在循环之外,或者如果引发异常,它不会被执行。

考虑它的一种方法是将其视为关于条件的 if/else 结构:

 if condition:
    handle_true()
else:
    handle_false()

类似于循环构造:

 while condition:
    handle_true()
else:
    # condition is false now, handle and go on with the rest of the program
    handle_false()

一个例子可能是这样的:

 while value < threshold:
    if not process_acceptable_value(value):
        # something went wrong, exit the loop; don't pass go, don't collect 200
        break
    value = update(value)
else:
    # value >= threshold; pass go, collect 200
    handle_threshold_reached()

原文由 ars 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题