# Learn Python The Hard Way学习(33) - While循环

2012-07-02

[python]
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

root@he-desktop:~/mystuff# 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循环写到一个函数中，用一个变量传递6这个值。
[python]
def while_function(i):
j = 0
numbers = []

while j < i:
numbers.append(j)
j += 1

return numbers

numbers = while_function(6)

2. 使用这个函数打印不同的数字。

3. 添加一个参数到函数中，让它可以根据这个参数修改增量值，就是i=i+1这里。
[python]
def while_function(i, increment):
j = 0
numbers = []

while j < i:
numbers.append(j)
j += increment

return numbers

numbers = while_function(6, 2)

4. 使用上面的函数运行一下。

5. 使用for循环和range函数实现上面的代码。
[python]
def for_function(i, increment):
numbers = []
for j in range(0, i, increment):
numbers.append(j)
return numbers

numbers = for_function(6, 2)