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

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

    I consider the structure as for (if) A else B, and for(if)-else is a special if-else, roughly. It may help to understand else.

    A and B is executed at most once, which is the same as if-else structure.

    for(if) can be considered as a special if, which does a loop to try to meet the if condition. Once the if condition is met, A and break; Else, B.

提交回复
热议问题