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

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

    Python uses an else after for and while loops so that if nothing applies to the loop, something else happens. For example:

    test = 3
    while test == 4:
         print("Hello")
    else:
         print("Hi")
    

    The output would be 'Hi' over and over again (if I'm correct).

提交回复
热议问题