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
加分习题
1. 将这个 while 循环改成一个函数,将测试条件(i < 6)中的 6 换成一个变量。
2. 使用这个函数重写你的脚本,并用不同的数字进行测试。
def list( i ):
numbers = []
j = 0
while j < i:
print("At the top number is %d" % j)
numbers.append(j)
j = j + 1
print "Numbers now: ", numbers
print("At the bottom number is %d" % j)
print("The numbers: ")
for num in numbers:
print(num)
print("Please type in a number:")
i = int(raw_input("> ")) //attention: raw_input()默认输入的是str,需要强制转换
list( i )
3. 为函数添加另外一个参数,这个参数用来定义第 8 行的加值 + 1 ,这样你就可以让它任意加值了。
4. 再使用该函数重写一遍这个脚本。看看效果如何。
def list( i, cut ):
numbers = []
j = 0
while j < i:
print("At the top number is %d" % j)
numbers.append(j)
j = j + cut
print "Numbers now: ", numbers
print("At the bottom number is %d" % j)
print("The numbers: ")
for num in numbers:
print(num)
print("Please type in a number:")
i = int(raw_input("> "))
print("Please type in cut off:")
cut = int(raw_input("> "))
list( i,cut)
5. 接下来使用 for-loop 和 range 把这个脚本再写一遍。你还需要中间的加值操作吗?如果你不去掉它,会有什么样的结果?
def list( i ):
numbers = []
j = 0
for j in range(0,i):
print("At the top number is %d" % j)
numbers.append(j)
print "Numbers now: ", numbers
print("At the bottom number is %d" % j)
print("The numbers: ")
for num in numbers:
print(num)
print("Please type in a number:")
i = int(raw_input("> "))
list( i )
range会自动遍历范围内的值,不需要j = j + 1