高级编程技术(Python)作业4

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

Solution:

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

Output:

1 8 27 64 125 216 343 512 729 1000 

注:使用end = “字符” 可以设置print的末尾,避免每一个元素都换行。

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:”,再使用切片来打印列表末尾的三个元素。

Solution:

cubes = [num ** 3 for num in range(1, 11)]
for cube in cubes:
    print(cube, end = " ")
print("\nThe first three items in the list are " + str(cubes[:3]))
print("Three items from the middle of the list are " + str(cubes[5:8]))
print("The last three items in the list are " + str(cubes[-3:]))

Output:

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 [216, 343, 512]
The last three items in the list are [512, 729, 1000]

注:对列表使用str强制类型转换会将中括号保留下来。

4-11 你的比萨和我的比萨:在你为完成练习4-1而编写的程序中,创建比萨列表的副本,并将其存储到变量friend_pizzas 中,再完成如下任务。
- 在原来的比萨列表中添加一种比萨。
- 在列表friend_pizzas 中添加另一种比萨。
- 核实你有两个不同的列表。为此,打印消息“My favorite pizzas are:”,再使用一个for 循环来打印第一个列表;打印消息“My friend’s favorite pizzas are:”,再使用一 个for 循环来打印第二个列表。核实新增的比萨被添加到了正确的列表中。

Solution:

pizzas = ["pepperoni", "mushroom", "hawaii"]
for pizza in pizzas:
    print("I like " + pizza + " pizza.")

print("\n" + pizzas[0].title() + " pizza is hot.")
print(pizzas[1].title() + " pizza is my favourite.")
print(pizzas[2].title() + " pizza is my dinner last night.")
print("I really love pizza!")

friend_pizzas = pizzas[:]
pizzas.append("salmon")
friend_pizzas.append("seafood")

print("\nMy favourite pizzas are", end = " ")
for pizza in pizzas[:2]:
    print(pizza + " pizza", end = ", ")
print(pizzas[-2]+ " pizza and " + pizzas[-1] + " pizza.")

print("\nMy friend's favourite pizzas are", end = " ")
for friend_pizza in friend_pizzas[:2]:
    print(friend_pizza + " pizza", end = ", ")
print(friend_pizzas[-2]+ " pizza and " + friend_pizzas[-1] + " pizza.")

Output:

扫描二维码关注公众号,回复: 1497499 查看本文章
I like pepperoni pizza.
I like mushroom pizza.
I like hawaii pizza.

Pepperoni pizza is hot.
Mushroom pizza is my favourite.
Hawaii pizza is my dinner last night.
I really love pizza!

My favourite pizzas are pepperoni pizza, mushroom pizza, hawaii pizza and salmon pizza.

My friend's favourite pizzas are pepperoni pizza, mushroom pizza, hawaii pizza and seafood pizza.

注:直接使用单纯的循环输出不符合英文的习惯说法,所以我对字符串进行了一些比较复杂的操作,让语句显得自然一点。

最后关于书中附录B中sublime的快捷键的使用:
- Ctrl + ] 可以将某一代码段同时缩进。
- Ctrl + [ 可以将某一代码段同时取消缩进。
- Ctrl + / 可以将某一代码段同时写为注释,再次使用就可以同时取消注释。

猜你喜欢

转载自blog.csdn.net/weixin_38311046/article/details/79594261
今日推荐