Python while else 语法有点特别,在其它的编程语言中是没有这种语法结构,其语法结构如下:
while [boolean expression]:
statement1
statement2
...
statementN
else:
else_statement1
else_statement2
...
else_statementN
看到语法结构我们很好理解了,它在原有while循环的基础上加上else语法,当while跳出循环的时候会同时执行else里面的代码块。举例说明Python while else 语法:
#!/usr/bin/python
# coding=utf-8
num =0
while num < 5:
num = num + 1
print('num = ', num)
else:
print('此时num大于等于5')
程序输出结果:num = 1
num = 2
num = 3
num = 4
num = 5
此时num大于等于5
num = 2
num = 3
num = 4
num = 5
此时num大于等于5