Python习题——2018-03-14作业

4-2 动物:想出至少三种有共同特征的动物,将这些动物的名称存储在一个列表中,再使用for循环将每种动物的名称都打印出来。
  • 修改这个程序,使其针对每种动物都打印一个句子,如"A dog would make a great pet"。
  • 在程序末尾添加一行代码,指出这些动物的共同之处,如打印诸如"Any of these animals would make a great pet!"这样的句子。
animals = ['tiger', 'lion', 'panther']
for animal in animals : 
	print(animal)
for animal in animals :
	print('The ' + animal + ' is fierce.')
print('Any of these animals is fierce!')

输出:

tiger
lion
panther
The tiger is fierce.
The lion is fierce.
The panther is fierce.
Any of these animals is fierce!


4-5 计算1~1 000 000的总和:创建一个列表,其中包含数字1~1 000 000,再使用min()和max()核实该列表确实是从1开始,到1 000 000结束的。另外,对这个列表调用函数sum(),看看Python将一百万个数字相加需要多长时间。

many_nums = list(range(1, 1000001))
print(min(many_nums))
print(max(many_nums))
print(sum(many_nums))

输出:

1
1000000
500000500000

[Finished in 0.1s]


4-9 立方解析:使用列表解析生成一个列表,其中包含前10个整数的立方。

nums = [i ** 3 for i in range(1, 11)]
for num in nums :
	print(num)

输出:

1
8
27
64
125
216
343
512
729
1000


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:",再使用切片来打印列表末尾的三个元素。
nums = [i ** 3 for i in range(1, 11)]
for num in nums :
	print(num) # 4-9题
print('The first three items in the list are: ', end = '')
print(nums[:3])
print('Three items from the middle of the list are: ', end = '')
print(nums[3:6])
print('The last three items in the list are: ', end = '')
print(nums[-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: [64, 125, 216]
The last three items in the list are: [512, 729, 1000]


4-13 自助餐:有一家自助式餐馆,只提供五种简单的食品。请想出五种简单的食品,并将其存储在一个元组中。

  • 使用一个for循环将该餐馆提供的五种食品都打印出来。
  • 尝试修改其中的一个元素,核实Python确实会拒绝你这样做。
  • 餐馆调整了菜单,替换了它提供的其中两种食品。请编写一个这样的代码块:给元组变量赋值,并使用一个for循环将新元组的每个元素都打印出来。
foods = ('hamburger', 'French fries', 'McChicken', 'McNuggets', 'Coke')
for food in foods :
	print(food)
print()
'''
foods(1) = 'Big Mac'
  File "<stdin>", line 1
SyntaxError: can't assign to function call
'''
foods = ('Big Mac', 'French fries', 'McChicken', 'McNuggets', 'sprite')
for food in foods :
	print(food)

输出:

hamburger
French fries
McChicken
McNuggets
Coke

Big Mac
French fries
McChicken
McNuggets
sprite

猜你喜欢

转载自blog.csdn.net/Draymond_666/article/details/79561821