动手试一试(ch.4)

4-2 动物:想出至少三种有共同特征的动物,将这些动物的名称存储在一个列表中,再使用for循环将每种动物的名称都打印出来。
修改这个程序,使其针对每种动物都打印一个句子,如“A dog would make a great pet”。
在程序末尾添加一行代码,指出这些动物的共同之处,如打印诸如“Any of these animals would make a great pet!”这样的句子。

animals = ['鸡', '猪', '鱼']
for animal in animals:
	print(animal, end = ' ');
print();
for animal in animals:
	print(animal + '肉很好吃');
print('这些动物都可以用来煲汤!')

输出:
鸡 猪 鱼
鸡肉很好吃
猪肉很好吃
鱼肉很好吃
这些动物都可以用来煲汤!

4-3 数到20 :使用一个for 循环打印数字1~20(含)。

for i in range(1, 21):
	print(i, end = ' ')

输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

4-6 奇数:通过给函数range() 指定第三个参数来创建一个列表,其中包含1~20的奇数;再使用一个for循环将这些数字都打印出来。
for i in range(1, 21, 2):
	print(i, end = ' ')

输出:
1 3 5 7 9 11 13 15 17 19

4-8 立方:将同一个数字乘三次称为立方。例如,在Python中,2的立方用2**3 表示。请创建一个列表,其中包含前10个整数(即1~10)的立方,再使用一个for 循 环将这些立方数都打印出来。
cubic = [x ** 3 for x in range(1, 11)]
for i in cubic:
	print(i, end = ' ')

输出:
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:”,再使用切片来打印列表末尾的三个元素。
l = list(range(1, 10))
print('The first three items in the list are:', l[:3])
print('Three items from the middle of the list are:', l[3:6])
print('The last three items in the list are:', l[6:])

输出:
The first three items in the list are: [1, 2, 3]
Three items from the middle of the list are: [4, 5, 6]
The last three items in the list are: [7, 8, 9]

4-13 自助餐:有一家自助式餐馆,只提供五种简单的食品。请想出五种简单的食品,并将其存储在一个元组中。
使用一个for 循环将该餐馆提供的五种食品都打印出来。
尝试修改其中的一个元素,核实Python确实会拒绝你这样做。
餐馆调整了菜单,替换了它提供的其中两种食品。请编写一个这样的代码块:给元组变量赋值,并使用一个for 循环将新元组的每个元素都打印出来。
foods = ('上校鸡块', '新奥尔良烤翅', '新奥尔良烤鸡腿堡', '老北京鸡肉卷', 'K记饭桶')
for food in foods:
	print(food)
foods = ('全家桶', '小薯条', '新奥尔良烤鸡腿堡', '老北京鸡肉卷', 'K记饭桶')
for food in foods:
	print(food)
foods[0] = '吮指原味鸡'

输出:
上校鸡块
新奥尔良烤翅
新奥尔良烤鸡腿堡
老北京鸡肉卷
K记饭桶
全家桶
小薯条
新奥尔良烤鸡腿堡
老北京鸡肉卷
K记饭桶
Traceback (most recent call last):
  File "a.py", line 7, in <module>
    foods[0] = '吮指原味鸡'
TypeError: 'tuple' object does not support item assignment

猜你喜欢

转载自blog.csdn.net/weixin_38196217/article/details/79561189
今日推荐