while 语句

 while 语句

while 语句

while 是循环语句之一,其形式为:

while 表达式:
    循环体

该语句会重复地检验表达式,当表达式为 True 时,会重复地执行循环体。以下代码将打印 Hello 5 次:

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

:这里在每次循环中将计数器 i 加 1 是非常有必要的,否则表达式将永远为 True,循环将无限进行下去。

while 还可以像 if 语句那样带一个 else 子句,当表达式为 False 时将执行 else 子句一次。如下所示:

i = 0
while i < 5:
    print('Hello')
    i += 1
else:
    print('Bye!')

以上代码将打印 Hello 5 次,打印 Bye! 一次。

match 语句for 语句