原文链接:http://learnpythonthehardway.org/book/ex33.html
接下来是一个更在你意料之外的概念: while-loop(while 循环)。在 while 循环中只要它的布尔表达式的值为True那么他就会一直执行while代码块中的代码。
等等,你应该能够理解我上面说的专业术语,对吧?如果我写了一个以 :(冒号)结尾的行那么就是告诉Python下面开始是一个新的代码块了,新的代码块是需要被缩进的。只有将代码用这样的方式格式化,Python 才能知道你的目的。如果你还是不明白,那你就要返回去做更多关于 if 语句,函数和for 循环的练习了直到你明白为止。
之后我们会有一些练习来训练你的大脑阅读这些结构,就像我们当时如何让你把布尔表达式记住一样。
回到while循环,其实它作用和if语句类似,不同的是if只执行一次它的代码块,而while执行完后会返回“顶部”的while那重新判断,再执行代码块,如此重复,直到它的判断的布尔表达式的值为False为止。
while循环也有个问题:有时候它是不会停止的。如果你打算让他一直循环直到世界末日,那这样也挺好的。否则的话,你通常还是希望循环最后终止的。
为了避免这些问题,你需要遵循下面这些规则:
1、确保尽量少用while循环,通常用一个for循环代替可能更好。
2、检查你的while部分的代码确保你的while循环的判断条件会在某个时候为Fales。
3、当你无法确认的时候,你可以将你的判断变量在while循环语句中的顶部和底部打印出来查看它的值,看看它在做什么变化。
在这次的练习中,你将通过做上面三件事情来学习while循环:
i = 0
numbers = []
while i < 6:
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ",numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
输出结果如下:
c:\>python ex33.py
At the top i is 0
Numbers now: [0]
At the bottom i is 1
At the top i is 1
Numbers now: [0, 1]
At the bottom i is 2
At the top i is 2
Numbers now: [0, 1, 2]
At the bottom i is 3
At the top i is 3
Numbers now: [0, 1, 2, 3]
At the bottom i is 4
At the top i is 4
Numbers now: [0, 1, 2, 3, 4]
At the bottom i is 5
At the top i is 5
Numbers now: [0, 1, 2, 3, 4, 5]
At the bottom i is 6
The numbers:
0
1
2
3
4
5
研究训练:
1、将while循环转换成一个你能够调用的函数,并且将判断条件(i < 6)中的6用一个变量来代替。def IncreaseNum(stepNum ,maxNum):
global i
while i < maxNum:
print "At the top i is %d" % i
numbers.append(i)
i = i + stepNum
print "Numbers now: ",numbers
print "At the bottom i is %d" % i
i = 0
numbers = []
IncreaseNum(2 ,6)
print "The numbers: "
for num in numbers:
print num
numbers = []
for i in range(0 , 6, 1):
print "At the top i is %d" % i
numbers.append(i)
print "Numbers now: ",numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
学生遇见的常见问题:
for循环和while循环有什么区别?
答:for循环是用来遍历序列对象内的元素,并对每个元素运行一个代码块,while循环提供了编写通用循环的一种方法。然而,通常while循环容易出错并且一般情况下很多事情用for循环就可以解决。
“循环很难理解”我该怎么理解这句话?
答:人们不能理解循环的主要原因是因为他们不能跟上代码的“跳跃”过程。当一个循环执行的时候,它先执行循环代码块,在运行到代码块的最后又跳回代码块的顶部执行。为了更好的看到这一点,应该在Python执行循环的代码中加上打印一些关键变量的语句。在循环之前,循环代码块顶部,循环代码块中间,循环代码块底部都可以加上打印语句。研究打印出来的变量的值试着去理解代码是怎么跳转的。