除了一般使用的for和while,还有一些用法:
# for 一般用法:
for i in range(5):
print(5)
# while 一般用法:
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
# while...else...语句:
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
# for...else...语句:
# pyton 的 for … else 中,for 中的语句和普通的没有区别,
# else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,
# while … else 也是一样。
for i in range(2, 9): # 找到 9 的非1最小因子
if 9 % i == 0: # 如果 i 是 9 的因子
print(i)
break # 跳出当前循环
else: # 如果在for里没执行break
print(9, '是一个质数')
# while 简单语句:
while (1): print('Hello!') # 无限输出‘Hello!’字符串
break,continue,pass:
break:结束,跳出循环
continue:直接进入下一次循环
pass:不执行任何操作,只占位(当没想好写什么语句是,没有pass,if语句或定义的函数会报错,所以用pass来占位,保证程序能运行下去)
for i in range(10):
if i == 5:
pass
#########
def function(x):
pass