4-1 比萨:想出至少三种你喜欢的比萨,将其名称存储在一个列表中,再使用for 循环将每种比萨的名称都打印出来。
·修改这个for 循环,使其打印包含比萨名称的句子,而不仅仅是比萨的名称。对于每种比萨,都显示一行输出,如“I like pepperoni pizza”。
·在程序末尾添加一行代码,它不在for 循环中,指出你有多喜欢比萨。输出应包含针对每种比萨的消息,还有一个总结性句子,如“I really love pizza!
pizzas=['chicken','pepperoni','beef']
for pizza in pizzas:
print("I like "+ pizza + " pizza")
输出:
I like chicken pizza
I like pepperoni pizza
I like beef pizza
4-3 数到20:使用一个for循环打印数字1~20(含)
for number in range(1,21):
print(number)
输出:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
4-7 3的倍数:创建一个列表,其中包含3~30内能被3整除的数字;再使用一个for循环将这个列表中的数字都打印出来
numbers=list(range(3,31,3))
for number in numbers:
print(number)
输出:
3
6
9
12
15
18
21
24
27
30
4-9 立方解析:使用列表解析生成一个列表,其中包含前10个整数的立方
numbers=[value**3 for value in range(1,11)]
print(numbers)
输出:
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
4-10 切片 :选择你在本章编写的一个程序,在末尾添加几行代码,以完成如下任务。
·打印消息“The first threeitems in thelistare:”,再使用切片来打印列表的前三个元素。
·打印消息“Three items fromthe middle ofthelistare:”,再使用切片来打印列表中间的三个元素。
·打印消息“The last threeitems in thelistare:”,再使用切片来打印列表末尾的三个元素。
numbers=[2,4,7,3,1,9,8]
print("The first three items in the list are:")
print(numbers[:3])
print("Three items from the middle of the list are:")
print(numbers[2:5])
print("The last three items in the list are:")
print(numbers[4:])
输出:
The first three items in the list are:
[2, 4, 7]
Three items from the middle of the list are:
[7, 3, 1]
The last three items in the list are:
[1, 9, 8]
4-11 你的比萨和我的比萨:在你为完成练习4-1而编写的程序中,创建比萨列表的副本,并将其存储到变量friend_pizzas 中,再完成如下任务。
·在原来的比萨列表中添加一种比萨。
·在列表friend_pizzas 中添加另一种比萨。
·核实你有两个不同的列表。为此,打印消息“My favorite pizzasare:”,再使用一个for 循环来打印第一个列表;打印消息“My friend’s favorite pizzasare:”,再使用一个for 循环来打印第二个列表。核实新增的比萨被添加到了正确的列表中。
pizzas=['beef','pepper','chicken']
friend_pizzas=pizzas[:]
pizzas.append('potato')
friend_pizzas.append('tomato')
print("My favorite pizzas are:")
for pizza in pizzas:
print(pizza)
print("My friend's favorite pizzas are:")
for friend_pizza in friend_pizzas:
print(friend_pizza)
输出:
My favorite pizzas are:
beef
pepper
chicken
potato
My friend's favorite pizzas are:
beef
pepper
chicken
tomato