Else clause on Python while statement

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

    The else clause is only executed when the while-condition becomes false.

    Here are some examples:

    Example 1: Initially the condition is false, so else-clause is executed.

    i = 99999999
    
    while i < 5:
        print(i)
        i += 1
    else:
        print('this')
    

    OUTPUT:

    this
    

    Example 2: The while-condition i < 5 never became false because i == 3 breaks the loop, so else-clause was not executed.

    i = 0
    
    while i < 5:
        print(i)
        if i == 3:
            break
        i += 1
    else:
        print('this')
    

    OUTPUT:

    0
    1
    2
    3
    

    Example 3: The while-condition i < 5 became false when i was 5, so else-clause was executed.

    i = 0
    
    while i < 5:
        print(i)
        i += 1
    else:
        print('this')
    

    OUTPUT:

    0
    1
    2
    3
    4
    this
    

提交回复
热议问题