#!usr/bin/python
# -*-coding:utf-8-*-

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)

运行结果如下:

$ 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

加分习题

将这个 while 循环改成一个函数,将测试条件(i < 6)中的 6 换成一个变量。

使用这个函数重写你的脚本,并用不同的数字进行测试。

为函数添加另外一个参数,这个参数用来定义第 8 行的加值 + 1 ,这样你就可以让它任意加值了。

再使用该函数重写一遍这个脚本。看看效果如何。

i = 0
numbers = []
test_num = input(">>>>>>> ")

while i in range(0,25):
	print ("At the top i is %d" %i)
	numbers.append(i)
	
	i = i + int(test_num)
	print ("Numbers now: ", numbers)
	print ("At the bottom i is %d" % i)

print ('The numbers:')

for num in numbers:
	print (num)

接下来使用 for-loop 和 range 把这个脚本再写一遍。你还需要中间的加值操作吗?如果你不去掉它,会有什么样的结果?

很有可能你会碰到程序跑着停不下来了,这时你只要按着 CTRL 再敲 c (CTRL-c),这样程序就会中断下来了。

常见问题回答

for-loop 和 while-loop 有何不同?

for-loop 只能对一些东西的集合进行循环, while-loop 可以对任何对象进行驯化。然而,while-loop 比起来更难弄对,而一般的任务用 for-loop更容易一些。

循环好难理解啊,我该怎样理解?

觉得循环不好理解,很大程度上是因为不会顺着代码的运行方式去理解代码。当循环开始时,它会运行整个区块,区块结束后回到开始的循环语句。如果想把整个过程视觉化,你可以在循环的各处塞入 print 语句,用来追踪变量的变化过程。你可以在循环之前、循环的第一句、循环中间、以及循环结尾都放一些 print 语句,研究最后的输出,并试着理解循环的工作过程。

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐