首页 > 代码库 > ex33.py

ex33.py

 1 i = 1
 2 numbers = []
 3 
 4 while i <= 8:
 5     print ("At the top i is %d" % i)
 6     numbers.append(i)
 7     i = i * 2
 8     print ("Numbers now:",numbers)
 9     print ("At the bottom i is %d" % i)
10 
11 
12 print ("The numbers:")
13 for num in numbers:
14     print (num)
15 
16 #应该看到的结果
17 At the top i is 1
18 Numbers now: [1]
19 At the bottom i is 2
20 At the top i is 2
21 Numbers now: [1, 2]
22 At the bottom i is 4
23 At the top i is 4
24 Numbers now: [1, 2, 4]
25 At the bottom i is 8
26 At the top i is 8
27 Numbers now: [1, 2, 4, 8]
28 At the bottom i is 16
29 The numbers:
30 1
31 2
32 4
33 8
34 
35 
36 nums = []
37 for i in range(1,9):
38     nums.append(i)
39     i = i * 2
40     print ("Numbers now:",nums)
41     print ("now i is : %d ," % i)   
42 ‘‘‘for 循环只能在一些集合中进行依次循环读取,后面的代码不影响for循环中集合中的依次读取数据,
43 比如上例中的i的取值在(1,9),那么for函数会按照顺序在(1,2,3,4,5,6,7,8)中依次读取这些集合中的数值,
44 不会因为 下面代码中的i = i * 2 就改变for 函数的读取数据。但是在while中是整个小脚本的循环,i的取值
45 会受到下面代码i = i * 2 的改变带来的影响,从而影响下一次循环中i 的取值‘‘‘
46 # 应该看到的结果
47 Numbers now: [1]
48 now i is : 2 ,
49 Numbers now: [1, 2]
50 now i is : 4 ,
51 Numbers now: [1, 2, 3]
52 now i is : 6 ,
53 Numbers now: [1, 2, 3, 4]
54 now i is : 8 ,
55 Numbers now: [1, 2, 3, 4, 5]
56 now i is : 10 ,
57 Numbers now: [1, 2, 3, 4, 5, 6]
58 now i is : 12 ,
59 Numbers now: [1, 2, 3, 4, 5, 6, 7]
60 now i is : 14 ,
61 Numbers now: [1, 2, 3, 4, 5, 6, 7, 8]
62 now i is : 16 ,

 

ex33.py