Else clause on Python while statement

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

    I know this is old question but...

    As Raymond Hettinger said, it should be called while/no_break instead of while/else.
    I find it easy to understeand if you look at this snippet.

    n = 5
    while n > 0:
        print n
        n -= 1
        if n == 2:
            break
    if n == 0:
        print n
    

    Now instead of checking condition after while loop we can swap it with else and get rid of that check.

    n = 5
    while n > 0:
        print n
        n -= 1
        if n == 2:
            break
    else:  # read it as "no_break"
        print n
    

    I always read it as while/no_break to understand the code and that syntax makes much more sense to me.

提交回复
热议问题