Else clause on Python while statement

前端 未结 12 2307
悲&欢浪女
悲&欢浪女 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 09:14

    The better use of 'while: else:' construction in Python should be if no loop is executed in 'while' then the 'else' statement is executed. The way it works today doesn't make sense because you can use the code below with the same results...

    n = 5
    while n != 0:
        print n
        n -= 1
    print "what the..."
    

提交回复
热议问题