引言:很久没有写 Python 了,有一点生疏。这是学习《Python 编程:从入门到实践(第3版)》的课后练习记录,主要目的是快速回顾基础知识。
想出至少三种你喜欢的比萨,将其名称存储在一个列表中,再使用for循环将每种比萨的名称打印出来。
I like pepperoni pizza.
I really love pizza!
pizzas = ["cheese", "pepperoni", "pineapple"]
for pizza in pizzas:
print(f"I like {pizza} pizza.")
print("I really love pizza!")
I like cheese pizza.
I like pepperoni pizza.
I like pineapple pizza.
I really love pizza!
知识点回顾:
[]
定义列表,元素之间用逗号 ,
分隔。for item in list_name:
。f
,并用花括号 {}
嵌入变量或表达式,方便构建动态字符串。print()
函数:用于将文本或变量的值输出到控制台。想出至少三种有共同特征的动物,将其名称存储在一个列表中,再使用for循环将每种动物的名称打印出来。
A dog would make a great pet.
Any of these animals would make a great pet!
animals = ["cat", "dog", "parrot"]
for animal in animals:
print(f"A {animal} would make a great pet.")
print("Any of these animals would make a great pet!")
A cat would make a great pet.
A dog would make a great pet.
A parrot would make a great pet.
Any of these animals would make a great pet!
知识点回顾:
for
循环外部使用 print()
函数输出总结性语句。使用一个for循环打印数1~20(含)。
for number in range(1, 21):
print(number)
1
2
3
... (输出将继续直到20)
19
20
知识点回顾:
range()
函数:用于生成一个数字序列。range(start, stop)
会生成从 start
开始到 stop-1
结束的整数序列。因此,range(1, 21)
会生成 1 到 20 的数字。for
循环与 range()
结合:常用于执行固定次数的迭代或遍历数字序列。创建一个包含数1~1 000 000的列表,再使用一个for循环将这些数打印出来。(如果输出的时间太长,按Ctrl + C停止输出,或关闭输出窗口。)
numbers = list(range(1, 1000001))
# 为了避免实际打印大量数据导致过长等待,以下循环通常会注释掉或只打印部分
# for number in numbers:
# print(number)
print("List created with 1,000,000 numbers. Printing is typically skipped for brevity.")
print(f"First few numbers: {numbers[:5]}")
print(f"Last few numbers: {numbers[-5:]}")
List created with 1,000,000 numbers. Printing is typically skipped for brevity.
First few numbers: [1, 2, 3, 4, 5]
Last few numbers: [999996, 999997, 999998, 999999, 1000000]
(注意:实际按题目要求运行 for number in numbers: print(number)
会输出1到100万所有数字,这里仅为演示列表创建)
知识点回顾:
list(range())
:将 range()
函数生成的序列直接转换为列表。Ctrl + C
来中断长时间运行的程序。创建一个包含数1~1 000 000的列表,再使用min()
和max()
核实该列表确实是从1开始、到1 000 000结束的。另外,对这个列表调用函数sum()
,看看Python将100万个数相加需要多长时间。
import time # 导入time模块来粗略计算时间
numbers = list(range(1, 1000001))
print(f"Min value: {min(numbers)}")
print(f"Max value: {max(numbers)}")
start_time = time.time()
total_sum = sum(numbers)
end_time = time.time()
print(f"Sum: {total_sum}")
print(f"Time taken to sum: {end_time - start_time:.6f} seconds")
Min value: 1
Max value: 1000000
Sum: 500000500000
Time taken to sum: 0.026786 seconds (时间会因机器性能而异)
知识点回顾:
min(list)
函数:返回列表中的最小值。max(list)
函数:返回列表中的最大值。sum(list)
函数:返回列表中所有数值型元素的和。sum()
)通常经过优化,执行效率较高。time
模块 (可选):可用于简单地测量代码段的执行时间。通过给range()
函数指定第三个参数来创建一个列表,其中包含1~20的奇数;再使用一个for循环将这些数打印出来。
odd_numbers = list(range(1, 21, 2))
for num in odd_numbers:
print(num)
1
3
5
7
9
11
13
15
17
19
知识点回顾:
range(start, stop, step)
函数:第三个参数 step
指定了序列中数字之间的步长(间隔)。range(1, 21, 2)
表示从1开始,不超过20,步长为2,从而生成奇数序列。创建一个列表,其中包含3~30内能被3整除的数,再使用一个for循环将这个列表中的数打印出来。
multiples_of_three = list(range(3, 31, 3))
for number in multiples_of_three:
print(number)
3
6
9
12
15
18
21
24
27
30
知识点回顾:
range()
与步长应用:通过设置合适的起始值、结束值和步长,可以方便地生成特定规律的数字序列,如倍数序列。将同一个数乘三次称为立方。例如,在Python中,2的立方用2**3
表示。创建一个列表,其中包含前10个整数(1~10)的立方,再使用一个for循环将这些立方数打印出来。
cubes = []
for i in range(1, 11):
cubes.append(i**3)
for number in cubes:
print(number)
1
8
27
64
125
216
343
512
729
1000
知识点回顾:
**
:用于计算乘方,x**y
表示 x 的 y 次方。append()
方法:用于在列表末尾添加新元素。使用列表推导式生成一个列表,其中包含前10个整数的立方。
cubes = [number**3 for number in range(1, 11)]
for number in cubes: # 或者直接 print(cubes)
print(number)
1
8
27
64
125
216
343
512
729
1000
知识点回顾:
[expression for item in iterable]
。它将 for
循环和元素创建合并在一行代码中,使代码更易读、更紧凑。选择你在本章编写的一个程序,在末尾添加几行代码,以完成如下任务。
# 沿用练习9的cubes列表
cubes = [number**3 for number in range(1, 11)]
print(f"The original list is: {cubes}")
print("\nThe first three items in the list are:")
print(cubes[:3])
# 为了选择中间的三个元素,我们需要确定列表长度和起始索引
# 列表长度为10,中间的三个可以是索引3, 4, 5或4, 5, 6等。
# 这里选择索引为列表长度整除2减1开始的三个,即第4、5、6个元素(索引3,4,5)
middle_start_index = len(cubes) // 2 - 1 # 对于长度10,这是 10//2 - 1 = 4
# 如果想更居中,对于偶数长度,可能需要更明确定义“中间”
# 这里简单选择从索引3开始的三个元素 (64, 125, 216)
print("\nThree items from the middle of the list are:")
print(cubes[3:6]) # 元素索引为3, 4, 5
print("\nThe last three items in the list are:")
print(cubes[-3:])
The original list is: [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:
[64, 125, 216]
The last three items in the list are:
[512, 729, 1000]
知识点回顾:
list_name[start:end]
:从索引 start
开始到 end-1
的元素。list_name[:end]
:从列表开头到 end-1
的元素。list_name[start:]
:从索引 start
到列表末尾的元素。list_name[-n:]
:列表末尾的 n
个元素。len()
函数:返回列表中的元素数量,可用于动态计算切片索引。在你为练习1编写的程序中,创建比萨列表的副本,并将其赋给变量friend_pizzas
,再完成如下任务。
friend_pizzas
中添加另一种比萨。pizzas = ["cheese", "pepperoni", "pineapple"]
friend_pizzas = pizzas[:] # 创建副本
pizzas.append("meat lover's")
friend_pizzas.append("mushroom")
print("My favorite pizzas are:")
for pizza in pizzas:
print(f"- {pizza}")
print("\nMy friend's favorite pizzas are:")
for pizza in friend_pizzas:
print(f"- {pizza}")
My favorite pizzas are:
- cheese
- pepperoni
- pineapple
- meat lover's
My friend's favorite pizzas are:
- cheese
- pepperoni
- pineapple
- mushroom
知识点回顾:
[:]
(如 friend_pizzas = pizzas[:]
) 可以创建一个列表的浅副本。这意味着对一个列表的修改(如 append()
)不会影响另一个列表。append()
方法:再次练习向列表末尾添加元素。在本节中,为节省篇幅,程序foods.py的每个版本都没有使用for循环来打印列表。请选择一个版本的foods.py,在其中编写两个for循环,将各个食品列表都打印出来。
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:] # 创建副本
# 假设我们对列表进行一些修改以展示它们是独立的
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
for food in my_foods:
print(f"- {food}")
print("\nMy friend's favorite foods are:")
for food in friend_foods:
print(f"- {food}")
My favorite foods are:
- pizza
- falafel
- carrot cake
- cannoli
My friend's favorite foods are:
- pizza
- falafel
- carrot cake
- ice cream
知识点回顾:
append()
方法以及使用 for
循环打印列表内容的巩固。for
循环分别处理和显示不同的数据集。\n
:在 print
语句中使用 \n
可以在输出中插入一个空行,使输出更易读。有一家自助式餐馆,只提供5种简单的食品。请想出5种简单的食品,并将其存储在一个元组中。
# 初始菜单
foods = ("牛肉", "鸡肉", "鱼肉", "蔬菜", "水果")
print("Original menu items:")
for food in foods:
print(f"- {food}")
# 尝试修改元组中的元素 (这将引发TypeError)
print("\nAttempting to change an item in the tuple...")
try:
foods[0] = "羊肉"
except TypeError as e:
print(f"Error: {e}")
# 餐馆调整菜单,创建一个新的元组
print("\nRestaurant is updating the menu.")
new_foods = ("牛肉", "鸡肉", "兔肉", "沙拉", "汤类") # 替换了鱼肉、蔬菜、水果
print("New menu items:")
for new_food in new_foods:
print(f"- {new_food}")
Original menu items:
- 牛肉
- 鸡肉
- 鱼肉
- 蔬菜
- 水果
Attempting to change an item in the tuple...
Error: 'tuple' object does not support item assignment
Restaurant is updating the menu.
New menu items:
- 牛肉
- 鸡肉
- 兔肉
- 沙拉
- 汤类
知识点回顾:
()
定义元组,元素之间用逗号 ,
分隔。TypeError
。for
循环遍历元组中的每个元素。new_foods = (...)
。这并没有改变原始的 foods
元组(如果它还在其他地方被引用的话),而是让 new_foods
指向了一个新的元组对象。try-except
块 (可选):用于捕获和处理预期的错误,如本例中的 TypeError
,使程序能优雅地处理错误而不是直接崩溃。