Exercise 33: While 循环

原文链接: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用一个变量来代替。
2、现在使用这个函数重写这个脚本,然后尝试不同的数值。
3、新增一个函数参数变量,将这个变量传进来到值来改变第8行的 +1操作,这样的话你就可以改变每次循环 i 增量多少。
4、再次使用过这个新的函数来改写脚本看看有什么效果。
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
5、接下来使用 for-loop 和 range 把这个脚本再写一遍。你还需要中间的加值操作吗?如果你不去掉它,会有什么样的结果?
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
很有可能你会碰到程序跑着停不下来了,这时你只要按着 CTRL 再敲 c (CTRL-c),这样程序就会中断下来了。

学生遇见的常见问题:

for循环和while循环有什么区别?
答:for循环是用来遍历序列对象内的元素,并对每个元素运行一个代码块,while循环提供了编写通用循环的一种方法。然而,通常while循环容易出错并且一般情况下很多事情用for循环就可以解决。

“循环很难理解”我该怎么理解这句话?
答:人们不能理解循环的主要原因是因为他们不能跟上代码的“跳跃”过程。当一个循环执行的时候,它先执行循环代码块,在运行到代码块的最后又跳回代码块的顶部执行。为了更好的看到这一点,应该在Python执行循环的代码中加上打印一些关键变量的语句。在循环之前,循环代码块顶部,循环代码块中间,循环代码块底部都可以加上打印语句。研究打印出来的变量的值试着去理解代码是怎么跳转的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值