Python课本第四章课后习题选做

4-2 动物 :想出至少三种有共同特征的动物,将这些动物的名称存储在一个列表中,再使用 for 循环将每种动物的名称都打印出来。
        a. 修改这个程序,使其针对每种动物都打印一个句子,如 “A dog would make a great pet” 。

        b. 在程序末尾添加一行代码,指出这些动物的共同之处,如打印诸如 “Any of these animals would make a great pet!” 这样的句子。

animals = ['dog','cat','bird']
for animal in animals:
    print('A ' + animal + ' would make a great pet.')
print('Any of these animals would make a great pet!')
A dog would make a great pet.
A cat would make a great pet.
A bird would make a great pet.
Any of these animals would make a great pet!
4-5 计算 1~1 000 000 的总和 :创建一个列表,其中包含数字 1~1 000 000 ,再使用 min() 和 max() 核实该列表确实是从 1 开始,到 1 000 000 结束的。另外,对这个列表调用函数 sum() ,看看 Python 将一百万个数字相加需要多长时间。
num = list(range(1,1000001))
print(max(num))
print(min(num))
print(sum(num))
1000000
1
500000500000
4-7 3 的倍数 :创建一个列表,其中包含 3~30 内能被 3 整除的数字;再使用一个 for 循环将这个列表中的数字都打印出来。
nums = list(range(3, 31, 3))
for num in nums:
    print(num)
3   
6   
9   
12  
15  
18  
21  
24  
27  
30  
4-9 立方解析 :使用列表解析生成一个列表,其中包含前 10 个整数的立方。
cube = [ value**3 for value in range(1,11)]
print(cube)
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
4-10 切片 :选择你在本章编写的一个程序,在末尾添加几行代码,以完成如下任务。
        a. 打印消息 “The first three items in the list are:” ,再使用切片来打印列表的前三个元素。
        b. 打印消息 “Three items from the middle of the list are:” ,再使用切片来打印列表中间的三个元素。
        c. 打印消息 “The last three items in the list are:” ,再使用切片来打印列表末尾的三个元素。
cube = [ value**3 for value in range(1,11)]
print(cube)

print('The first three items in the list are:' + str(cube[:3]))
print('Three items from the middle of the list are:' + str(cube[int(len(cube)/2)-1:int(len(cube)/2)+2]))
print('The last three items in the list are:' + str(cube[-3:]))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
The first three items in the list are:[1, 8, 27]
Three items from the middle of the list are:[125, 216, 343]
The last three items in the list are:[512, 729, 1000]
4-12 使用多个循环 :在本节中,为节省篇幅,程序 foods.py 的每个版本都没有使用 for 循环来打印列表。请选择一个版本的 foods.py ,在其中编写两个 for 循环,将各个食品列表都打印出来。
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
print("My favorite foods are:")
for food in my_foods:
    print(food)
print("\nMy friend's favorite foods are:")
for food in friend_foods:
    print(food)
My favorite foods are:
pizza
falafel
carrot cake

My friend's favorite foods are:
pizza
falafel
carrot cake








你可能感兴趣的:(Python课本第四章课后习题选做)