该章主要讲述了列表的遍历(使用for循环来遍历列表),还有遍历部分列表(列表的切片[ : ]),还有关于不可修改的列表——元组。
4-2 动物
题目描述:
想出至少三种有共同特征的动物,将这些动物的名称存储在一个列表中,再使用for 循环将每种动物的名称都打印出来。
修改这个程序,使其针对每种动物都打印一个句子,如“A dog would make a great pet”。
在程序末尾添加一行代码,指出这些动物的共同之处,如打印诸如“Any of these animals would make a great pet!”这样的句子。
INPUT:
None
OUTPUT:
A dog would make a great pet
A cat would make a great pet
A tiger would make a great pet
A bird would make a great pet
Any of these animals would make a great pets
代码展示:
Animals = ["dog", "cat", "tiger", "bird"]
for animal in Animals:
print("A " + animal + " would make a great pet")
print("Any of these animals would make a great pets")
4-5 计算1~1 000 000的总和
题目描述:
INPUT:
None
OUTPUT:
Min number is:1
Max number is:1000000
Sum of number is:500000500000
Use tme: 0:00:00.054332
代码展示:
import datetime
nums = range(1, 1000001)
print("Min number is:"+ str(min(nums)))
print("Max number is:"+ str(max(nums)))
starttime = datetime.datetime.now()
print("Sum of number is:"+ str(sum(nums)))
endtime = datetime.datetime.now()
print ("Use tme: "+ str(endtime - starttime) + "s")
4-10 切片
题目描述:
选择你在本章编写的一个程序,在末尾添加几行代码,以完成如下任务。
打印消息“The first three items in the list are:”,再使用切片来打印列表的前三个元素。
打印消息“Three items from the middle of the list are:”,再使用切片来打印列表中间的三个元素。
打印消息“The last three items in the list are:”,再使用切片来打印列表末尾的三个元素。
INPUT:
None
OUTPUT:
First three items:['a', 'b', 'c']
Middle three items:['c', 'd', 'e']
Last three items:['e', 'f', 'g']
代码展示:
nums = ["a", "b", "c", "d", "e", "f", "g"]
print("First three items:" + str(nums[0:3]))
print("Middle three items:" + str(nums[2:5]))
print("Last three items:" + str(nums[-3:]))
4-13 自助餐
题目描述:
有一家自助式餐馆,只提供五种简单的食品。请想出五种简单的食品,并将其存储在一个元组中。使用一个for 循环将该餐馆提供的五种食品都打印出来。
尝试修改其中的一个元素,核实Python确实会拒绝你这样做。
INPUT:
None
OUTPUT:
There is onion in resturant
Traceback (most recent call last):
There is egg in resturant
File "D:/study/Programming/Code Python/tmp.py", line 5, in <module>
There is chicken in resturant
There is beef in resturant
There is pork in resturant
foods[0]='bread'
TypeError: 'tuple' object does not support item assignment
代码展示:
foods = ('onion','egg','chicken','beef','pork')
for food in foods:
print("There is " + food + " in resturant")
foods[0]='bread'