(Week 2)Python编程:从入门到实践(习题4-1至4-15选做)

4-2 动物:(1)想出至少三种有共同特征的动物,将这些动物的名称存储在一个列表中,再使用for循环将每种动物的名称都打印出来。 

                (2)修改这个程序,使其针对每种动物都打印一个句子,如“A dog would make a great pet”。

                (3)在程序末尾添加一行代码,指出这些动物的共同之处

list1 = ['dog', 'fish', 'parrot']
for each in list1:
    print(each + ' would make a great pet!')
print('Any of these animals would make a great pet!')
>>> 
========================== RESTART: D:/python/a.py ==========================
dog would make a great pet!
fish would make a great pet!
parrot would make a great pet!
Any of these animals would make a great pet!

4-7 3的倍数:创建一个列表,其中包含3~30内能被3整除的数字;再使用一个for 循环将这个列表中的数字都打印出来。 

>>> list1 = list(range(3, 31, 3))
>>> for each in list1:
	print(each, end = ' ')

	
3 6 9 12 15 18 21 24 27 30 

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

>>> list2 = [x ** 3 for x in range(1, 11)]
>>> for each in list2:
	print(each, end = ' ')

	
1 8 27 64 125 216 343 512 729 1000 

4-10 切片:选择你在本章编写的一个程序,在末尾添加几行代码,以完成如下任务。 

                (1)打印消息“The first three items in the list are:”,再使用切片来打印列表的前三个元素。 

                (2)打印消息“Three items from the middle of the list are:”,再使用切片来打印列表中间的三个元素。 

                (3)打印消息“The last three items in the list are:”,再使用切片来打印列表末尾的三个元素。

list1 = list(range(3, 31, 3))
for each in list1:
    print(each, end = ' ')
print('\nThe first three items in the list are:', end = '')
for each in list1[:3]:
    print(each, end = ' ')
print('\nThree items from the middle of the list are:', end = '')
for each in list1[4:7]:
    print(each, end = ' ')
print('\nThe last three items in the list are:', end = '')
for each in list1[-3:]:
    print(each, end = ' ')
========================== RESTART: D:/python/a.py ==========================
3 6 9 12 15 18 21 24 27 30 
The first three items in the list are:3 6 9 
Three items from the middle of the list are:15 18 21 
The last three items in the list are:24 27 30 
>>> 

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

                     (2)使用一个for 循环将该餐馆提供的五种食品都打印出来。

                    (3)餐馆调整了菜单,替换了它提供的其中两种食品。请编写一个这样的代码块:给元组变量赋值,并使用一个for 循环将新元组的每个元素都打印出来。 

tuple1 = ('beef', 'pork', 'chicken', 'vegetable', 'fruit')
for each in tuple1:
    print(each, end = ' ')
print()
tuple1 = ('beef', 'rice', 'fish', 'vegetable', 'fruit')
for each in tuple1:
    print(each, end = ' ')
========================== RESTART: D:/python/a.py ==========================
beef pork chicken vegetable fruit 
beef rice fish vegetable fruit 
>>> 


 



  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值