循环(looping),计数循环(counting loop),条件循环(conditional loop)。
1 计数循环,for循环
for looper in [1,2,3,4,5]:
print "hello"
每一次循环称为一次迭代(iteration)。
再来试试看
for looper in [1,2,3,4,5]:
print looper
这次和上次显示的不同,是不是,如果循环出错形成无限循环怎么办啊,中断循环(CTRL+C)。
再来是一个有意义点的程序,8的乘法表
for looper in [1,2,3,4,5]:
print looper, "times 8 =", looper * 8
运行结果如下
>>> ================================ RESTART ================================
>>>
1 times 8 = 8
2 times 8 = 16
3 times 8 = 24
4 times 8 = 32
5 times 8 = 40
循环函数range(),
for looper in range (1,5):
print looper, "times 8 =", looper * 8
运行结果如下
>>> ================================ RESTART ================================
>>>
1 times 8 = 8
2 times 8 = 16
3 times 8 = 24
4 times 8 = 32
和上面显示的结果有点不一样,为什么呢?
range(),提供一个数字列表,从给的第一个数开始,在给的的最后一个数之前结束。必须要注意到这一点。
再来一个例子,8的乘法表(从1到10)
for looper in range (1,11):
print looper, "times 8 =", looper * 8
循环变量命名的通用惯例:习惯用i,j,k作为循环变量,不应当有其他用途。例如
for i in range (1,5):
print i, "times 8 =", i * 8
range()的简写
for i in range (5):
# 与写作 for i in range (0, 5): 完全相同
print i, "times 8 =", i * 8
大多数的程序都从0开始循环而不是从1开始。range()默认从0开始,步长为1.如果想步长为2计数,可以这样
for i in range (1,10,2):
print i
反向计数
for i in range (10, 1, -1):
print i
再来个反向计数的例子,步长为-1后循环作反向计数
# 与孩子一起学编程08章
# 2013年8月27日14:03:52
# range()循环反向计数-2 8-10
import time
for i in range (10, 0, -1):
print i
time.sleep(1)
print "BLAST OFF!"
没有数字的计数循环
for cool_guy in ["Spongebob", "Spoderman", "Justin Timberlake", "My Dad"]:
print cool_guy, "is the coolest guy ever!"
运行结果
>>>
Spongebob is the coolest guy ever!
Spoderman is the coolest guy ever!
Justin Timberlake is the coolest guy ever!
My Dad is the coolest guy ever!
>>>
2 条件循环,while循环
如果能提前知道希望循环运行多少次,那么for循环挺合适。不过,有时希望循环一直运行下去,直到发生某种情况时才结束,而且不知道发生这种情况之前会有多少次迭代。这就可以用while循环来实现。
print "Type 3 to continue, anything else to quit."
someInput = raw_input()
while someInput == '3':
print "Thank you for the 3. Very kind of you."
print "Type 3 to continue, anything else to quit."
someInput = raw_input()
print "That's not 3, so I'm quitting now."
运行结果
>>>
Type 3 to continue, anything else to quit.
3
Thank you for the 3. Very kind of you.
Type 3 to continue, anything else to quit.
3
Thank you for the 3. Very kind of you.
Type 3 to continue, anything else to quit.
3
Thank you for the 3. Very kind of you.
Type 3 to continue, anything else to quit.
5
That's not 3, so I'm quitting now.
>>>
3 跳出循环——break和continue
用continue直接跳到循环的下一次迭代,或者用break完全终止循环。
先来看continue的用法
for i in range (1, 6):
print
print 'i =', i,
print 'Hello, how',
if i == 3:
continue
print 'are you today?'
运行结果
>>>
i = 1 Hello, how are you today?
i = 2 Hello, how are you today?
i = 3 Hello, how
i = 4 Hello, how are you today?
i = 5 Hello, how are you today?
break的用法
for i in range (1, 6):
print
print 'i =', i,
print 'Hello, how',
if i == 3:
break
print 'are you today?'
运行结果
>>>
i = 1 Hello, how are you today?
i = 2 Hello, how are you today?
i = 3 Hello, how
>>>
从上两个程序能看出continue和break的用法和区别吗?
好了,python中的循环学习就到这儿,上一章的if,条件和测试,及这一章中计数循环和条件循环,差不多了吧,我都跃跃欲试了,呵呵。