python中while与else的联姻

时间:2022-12-13 14:36:10

循环使用 else 语句
在 python 中,for … else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while … else 也是一样。

#!/usr/bin/python

count = 0
while count < 5:
  print count, " is less than 5"
  count = count + 1
else: #其实此处的count已经不满足<5的条件了,while此处类似if的作用了.
  print count, " is not less than 5"

以上实例输出结果为:

0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5