Else clause on Python while statement

前端 未结 12 2175
悲&欢浪女
悲&欢浪女 2020-11-22 08:24

I\'ve noticed the following code is legal in Python. My question is why? Is there a specific reason?

n = 5
while n != 0:
    print n
    n -= 1
else:
    pri         


        
12条回答
  •  醉酒成梦
    2020-11-22 08:59

    The else: statement is executed when and only when the while loop no longer meets its condition (in your example, when n != 0 is false).

    So the output would be this:

    5
    4
    3
    2
    1
    what the...
    

提交回复
热议问题