Else clause on Python while statement

前端 未结 12 2271
悲&欢浪女
悲&欢浪女 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:07

    Else is executed if while loop did not break.

    I kinda like to think of it with a 'runner' metaphor.

    The "else" is like crossing the finish line, irrelevant of whether you started at the beginning or end of the track. "else" is only not executed if you break somewhere in between.

    runner_at = 0 # or 10 makes no difference, if unlucky_sector is not 0-10
    unlucky_sector = 6
    while runner_at < 10:
        print("Runner at: ", runner_at)
        if runner_at == unlucky_sector:
            print("Runner fell and broke his foot. Will not reach finish.")
            break
        runner_at += 1
    else:
        print("Runner has finished the race!") # Not executed if runner broke his foot.
    

    Main use cases is using this breaking out of nested loops or if you want to run some statements only if loop didn't break somewhere (think of breaking being an unusual situation).

    For example, the following is a mechanism on how to break out of an inner loop without using variables or try/catch:

    for i in [1,2,3]:
        for j in ['a', 'unlucky', 'c']:
            print(i, j)
            if j == 'unlucky':
                break
        else: 
            continue  # Only executed if inner loop didn't break.
        break         # This is only reached if inner loop 'breaked' out since continue didn't run. 
    
    print("Finished")
    # 1 a
    # 1 b
    # Finished
    

提交回复
热议问题