Else clause on Python while statement

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

    The else-clause is executed when the while-condition evaluates to false.

    From the documentation:

    The while statement is used for repeated execution as long as an expression is true:

    while_stmt ::=  "while" expression ":" suite
                    ["else" ":" suite]
    

    This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates.

    A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and goes back to testing the expression.

提交回复
热议问题