跟老齐学Python之用while来循环(3)
#!/usr/bin/env python
#coding:utf-8
a = 9
while a:
if a%2==0:
a -=1
continue #如果是偶数,就返回循环的开始
else:
print "%d is odd number"%a #如果是奇数,就打印出来
a -=1
其实,对于这两东西,我个人在编程中很少用到。我有一个固执的观念,尽量将条件在循环之前做足,不要在循环中跳来跳去,不仅可读性下降,有时候自己也糊涂了。
while...else
这两个的配合有点类似if ... else,只需要一个例子列为就理解了,当然,一遇到else了,就意味着已经不在while循环内了。
#!/usr/bin/env python
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
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
- 上一篇:跟老齐学Python之for循环语句
- 下一篇:跟老齐学Python之复习if语句






