Why does python use 'else' after for and while loops?

前端 未结 21 1903
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 06:57

I understand how this construct works:

for i in range(10):
    print(i)

    if i == 9:
        print(\"Too big - I\'m         


        
21条回答
  •  悲哀的现实
    2020-11-21 07:27

    The easiest way I found to 'get' what the for/else did, and more importantly, when to use it, was to concentrate on where the break statement jumps to. The For/else construct is a single block. The break jumps out of the block, and so jumps 'over' the else clause. If the contents of the else clause simply followed the for clause, it would never be jumped over, and so the equivalent logic would have to be provided by putting it in an if. This has been said before, but not quite in these words, so it may help somebody else. Try running the following code fragment. I'm wholeheartedly in favour of the 'no break' comment for clarity.

    for a in range(3):
        print(a)
        if a==4: # change value to force break or not
            break
    else: #no break  +10 for whoever thought of this decoration
        print('for completed OK')
    
    print('statement after for loop')
    

提交回复
热议问题