Python while语句的其他子句

发布于 2021-02-02 23:16:56

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

n = 5
while n != 0:
    print n
    n -= 1
else:
    print "what the..."
关注者
0
被浏览
52
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    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()
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看