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

前端 未结 21 1916
爱一瞬间的悲伤
爱一瞬间的悲伤 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:31

    To make it simple, you can think of it like that;

    • If it encounters the break command in the for loop, the else part will not be called.
    • If it does not encounter the break command in the for loop, the else part will be called.

    In other words, if for loop iteration is not "broken" with break, the else part will be called.

提交回复
热议问题