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

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

    I was just trying to make sense of it again myself. I found that the following helps!

    • Think of the else as being paired with the if inside the loop (instead of with the for) - if condition is met then break the loop, else do this - except it's one else paired with multiple ifs!
    • If no ifs were satisfied at all, then do the else.
    • The multiple ifs can also actually be thought of as if-elifs!

提交回复
热议问题