一尘不染

Python while语句的其他子句

python

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

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

阅读 402

收藏
2020-02-18

共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()
2020-02-18