Else clause on Python while statement

前端 未结 12 2359
悲&欢浪女
悲&欢浪女 2020-11-22 08:24

I\'ve noticed the following code is legal in Python. My question is why? Is there a specific reason?

n = 5
while n != 0:
    print n
    n -= 1
else:
    pri         


        
12条回答
  •  时光说笑
    2020-11-22 09:09

    The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won't be executed.

    One way to think about it is as an if/else construct with respect to the condition:

    if condition:
        handle_true()
    else:
        handle_false()
    

    is analogous to the looping construct:

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

    An example might be along the lines of:

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

提交回复
热议问题