Exercise 32
代码
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" % number
# same as above
for fruit in fruits:
print "A fruit of type: %s" % fruit
# also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in change:
print "I got %r" % i
# we can also build lists, first start with an empty one
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0,6):
print "Adding %d to the list." % i
# append is a function that lists understand
elements.append(i)
# now we can print them out too
for i in elements:
print "Element was: %d" % i
输出
Notes:
①range(start,end)返回一个整型序列,范围是start至end-1
>>> range(0.6)
[0, 1, 2, 3, 4, 5]
②for...in...迭代循环适用于字符串、列表等序列类型
③序列之间可以用加号相连,组成新序列
>>> elements = []
>>> elements + range(0,6)
[0, 1, 2, 3, 4, 5]
Exercise 33
代码
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
输出
Notes:
①while通过检查布尔表达式的真假来确定循环是否继续。除非必要,尽量少用while-loop,大部分情况下for-loop是更好的选择;使用while-loop时注意检查布尔表达式的变化情况,确保其最终会变成False,除非你想要的就是无限循环
②加分习题一代码改写
代码
i = 0
numbers = []
def numbers_list(x):
global numbers, i
while i < x:
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
numbers_list(7)
print "The numbers:"
for num in numbers:
print num
输出
PS:函数需注意局部变量和全局变量的问题。
③加分习题二代码改写
代码
i = 0
numbers = []
def numbers_list(x, y):
global numbers, i
while i < x:
print "At the top i is %d" % i
numbers.append(i)
i = i + y
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
numbers_list(7, 3)
print "The numbers:"
for num in numbers:
print num
输出
Exercise 34
本节无代码,主要练习列表的切片、序数与基数问题
练习:
The animal at 1 is the 2nd animal and is a python.
The 3rd animal is at 2 and is a peocock.
The 1st animal is at 0 and is a bear.
The animal at 3 is the 4th animal and is a kanaroo.
The 5th animal is at 4 and is a whale.
The animal at 2 is the 3rd animal and is a peocock.
The 6th animal is at 5 and is a platypus.
The animal at 4 is the 5th and is a whale.