Python 中,无论是 while 循环还是 for 循环,其后都可以紧跟着一个 else 代码块,它的作用是,当循环条件为 False 跳出循环时,程序会最先执行 else 代码块中的代码。
如下代码示范了为 while 循环定义 else 代码块:
count_i = 0
while count_i < 5:
print('count_i小于5: ', count_i)
count_i += 1
else:
print('count_i大于或等于5: ', count_i)
运行上面程序,可以看到如下输出结果:
count_i小于5: 0
count_i小于5: 1
count_i小于5: 2
count_i小于5: 3
count_i小于5: 4
count_i大于或等于5: 5
从上面的运行过程来看,当循环条件 count i < 5 变成 False 时,程序执行了 while 循环的 else 代码块。
简单来说,程序在结束循环之前,会先执行 else 代码块。从这个角度来看,else 代码块其实没有太大的价值,将 else 代码块直接放在循环体之外即可。也就是说,上面代码其实可改为如下形式:
count_i = 0
while count_i < 5:
print('count_i小于5: ', count_i)
count_i += 1
print('count_i大于或等于5: