Chapter4:列表操作 课后习题选做

4-1 比萨 :想出至少三种你喜欢的比萨,将其名称存储在一个列表中,再使用for 循环将每种比萨的名称都打印出来。

  • 修改这个for 循环,使其打印包含比萨名称的句子,而不仅仅是比萨的名称。对于每种比萨,都显示一行输出,如“I like pepperoni pizza”
  • 在程序末尾添加一行代码,它不在for 循环中,指出你有多喜欢比萨。输出应包含针对每种比萨的消息,还有一个总结性句子,如“I really love pizza!”

代码1如下

pizzas = ['kind_a','kind_b','kind_c']
for pizza in pizzas:
    print(pizza)

代码2如下

pizzas = ['kind_a','kind_b','kind_c']
for pizza in pizzas:
    print('I like '+ pizza + ' pizza')

代码3如下

pizzas = ['kind_a','kind_b','kind_c']
for pizza in pizzas:
    print('I like '+ pizza + ' pizza')
print('I really love pizza')

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

代码如下:

for num in range(1,21):
    print(num)

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

代码如下:

nums = list(range(1,21,2))
for num in nums:
    print(num)

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

代码如下:

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

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 = list(range(1,11))
print('The first three items in the list are:')
print(nums[:3])
print('Three items from the middle of the list are:')
print(nums[int(len(nums)/2):])
print('The last three items in the list are:')
print(nums[-3:])

#The results are as follows:
'''
The first three items in the list are:
[1, 2, 3]
Three items from the middle of the list are:
[6, 7, 8, 9, 10]
The last three items in the list are:
[8, 9, 10]
'''
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值