引言:很久没有写 Python 了,有一点生疏。这是学习《Python 编程:从入门到实践(第3版)》的课后练习记录,主要目的是快速回顾基础知识。
练习1:条件测试
编写一系列条件测试,将每个条件测试以及你对其结果的预测和实际结果都打印出来。你编写的代码应类似于下面这样:
car = 'subaru'
print("is car == 'subaru'? I predict True.")
print(car == 'subaru')
print("\nis car == 'audi'? I predict False.")
print(car == 'audi')
- 详细研究实际结果,直到你明白它为何为True或False。
- 创建至少10个条件测试,而且结果为True和False的条件测试分别至少有5个。
# 定义一些变量用于测试
car = 'subaru'
animal = 'dog'
age = 25
temperature = 30.5
colors = ['red', 'green', 'blue']
is_active = True
username = 'Admin'
# --- 结果为 True 的测试 (5个) ---
# 测试 1: 检查 car 是否等于 'subaru'
print("测试 1: car == 'subaru' 吗? 我预测结果为 True.")
print(car == 'subaru')
# 测试 2: 检查 animal 是否不等于 'cat'
print("\n测试 2: animal != 'cat' 吗? 我预测结果为 True.")
print(animal != 'cat')
# 测试 3: 检查 age 是否大于等于 18
print("\n测试 3: age >= 18 吗? 我预测结果为 True.")
print(age >= 18)
# 测试 4: 检查 'green' 是否在 colors 列表中
print("\n测试 4: 'green' in colors 吗? 我预测结果为 True.")
print('green' in colors)
# 测试 5: 检查 is_active 是否为 True
print("\n测试 5: is_active 吗? 我预测结果为 True.") # 直接检查布尔变量
print(is_active)
# --- 结果为 False 的测试 (5个) ---
# 测试 6: 检查 car 是否等于 'audi'
print("\n测试 6: car == 'audi' 吗? 我预测结果为 False.")
print(car == 'audi')
# 测试 7: 检查 age 是否小于 20
print("\n测试 7: age < 20 吗? 我预测结果为 False.")
print(age < 20)
# 测试 8: 检查 temperature 是否严格等于 30 (注意浮点数比较)
print("\n测试 8: temperature == 30 吗? 我预测结果为 False.")
print(temperature == 30) # 30.5 不等于 30
# 测试 9: 检查 'yellow' 是否在 colors 列表中
print("\n测试 9: 'yellow' in colors 吗? 我预测结果为 False.")
print('yellow' in colors)
# 测试 10: 检查 username.lower() 是否等于 'admin' 的同时 age 是否大于 30 (使用 and)
# username.lower() 是 'admin' (True), age > 30 是 False (25 > 30 is False)
# True and False 结果是 False
print("\n测试 10: username.lower() == 'admin' and age > 30 吗? 我预测结果为 False.")
print(username.lower() == 'admin' and age > 30)
测试 1: car == 'subaru' 吗? 我预测结果为 True.
True
测试 2: animal != 'cat' 吗? 我预测结果为 True.
True
测试 3: age >= 18 吗? 我预测结果为 True.
True
测试 4: 'green' in colors 吗? 我预测结果为 True.
True
测试 5: is_active 吗? 我预测结果为 True.
True
测试 6: car == 'audi' 吗? 我预测结果为 False.
False
测试 7: age < 20 吗? 我预测结果为 False.
False
测试 8: temperature == 30 吗? 我预测结果为 False.
False
测试 9: 'yellow' in colors 吗? 我预测结果为 False.
False
测试 10: username.lower() == 'admin' and age > 30 吗? 我预测结果为 False.
False
知识点回顾:
- 变量赋值:为不同类型的变量(字符串
str
, 整数int
, 浮点数float
, 列表list
, 布尔值bool
)赋值。 - 比较运算符:
==
(等于)!=
(不等于)>=
(大于等于)<
(小于)
- 成员运算符:
in
(检查元素是否存在于序列中,如列表)。 - 布尔值:
True
和False
,可以直接用于条件判断。 - 逻辑运算符:
and
(逻辑与,两边都为True
时结果才为True
)。 - 字符串方法:
.lower()
(将字符串转换为小写,常用于不区分大小写的比较)。 - 浮点数比较:直接用
==
比较浮点数可能因精度问题产生意外结果,但在此例中30.5 == 30
的比较是明确的False
。 print()
函数:用于输出文本和表达式的结果。
练习2:外星人颜色1
假设玩家在游戏中消灭了一个外星人,请创建一个名为alien_color
的变量,并将其赋值为'green'
、'yellow'
或'red'
。
- 编写一条
if
语句,测试外星人是否是绿色的。如果是,就打印一条消息,指出玩家获得了5分。 - 编写这个程序的两个版本,上述条件测试在其中的一个版本中通过,在另一个版本中未通过(未通过条件测试时没有输出)。
alien_color = "green"
if alien_color == "green":
print("You just earned 5 points!")
alien_color = "red" # 第二个版本,条件不通过
if alien_color == "green":
print("You just earned 5 points!") # 这条不会打印
You just earned 5 points!
知识点回顾:
- 变量赋值:将字符串
'green'
或'red'
赋给变量alien_color
。 if
语句:用于执行条件判断。如果if
后的条件表达式为True
,则执行其下的代码块。- 条件表达式:
alien_color == "green"
使用等于运算符==
比较变量值和字符串字面量。 - 代码块缩进:Python 使用缩进来定义代码块的范围。
练习3:外星人颜色2
像练习2那样设置外星人的颜色,并编写一个if-else
结构。
- 如果外星人是绿色的,就打印一条消息,指出玩家因消灭该外星人获得了5分。
- 如果外星人不是绿色的,就打印一条消息,指出玩家获得了10分。
- 编写这个程序的两个版本,在一个版本中将执行
if
代码块,在另一个版本中将执行else
代码块。
# 版本1: 执行 if 代码块
alien_color = "green"
if alien_color == "green":
print("You just earned 5 points!")
else:
print("You just earned 10 points!")
# 版本2: 执行 else 代码块
alien_color = "yellow"
if alien_color == "green":
print("You just earned 5 points!")
else:
print("You just earned 10 points!")
You just earned 5 points!
You just earned 10 points!
知识点回顾:
if-else
结构:提供两种可能的执行路径。如果if
条件为True
,执行if
下的代码块;否则 (条件为False
),执行else
下的代码块。- 互斥条件:
if
和else
对应的代码块是互斥的,只会执行其中一个。
练习4:外星人颜色3
将练习3中的if-else
结构改为if-elif-else
结构。
- 如果外星人是绿色的,就打印一条消息,指出玩家获得了5分。
- 如果外星人是黄色的,就打印一条消息,指出玩家获得了10分。
- 如果外星人是红色的,就打印一条消息,指出玩家获得了15分。
- 编写这个程序的三个版本,分别在外星人为绿色、黄色和红色时打印一条消息。
# 版本1: 绿色外星人
alien_color = "green"
if alien_color == "green":
print("You just earned 5 points!")
elif alien_color == "yellow":
print("You just earned 10 points!")
else: # 假设只有这三种颜色,所以红色会进入else
print("You just earned 15 points!")
# 版本2: 黄色外星人
alien_color = "yellow"
if alien_color == "green":
print("You just earned 5 points!")
elif alien_color == "yellow":
print("You just earned 10 points!")
else:
print("You just earned 15 points!")
# 版本3: 红色外星人
alien_color = "red"
if alien_color == "green":
print("You just earned 5 points!")
elif alien_color == "yellow":
print("You just earned 10 points!")
else: # 也可以写成 elif alien_color == "red": print(...)
print("You just earned 15 points!")
You just earned 5 points!
You just earned 10 points!
You just earned 15 points!
知识点回顾:
if-elif-else
结构:用于检查多个互斥条件。Python 会按顺序检查每个if
或elif
条件,一旦找到为True
的条件,就执行其对应的代码块,并跳过其余的elif
和else
子句。elif
(else if):允许添加更多的条件分支。else
(可选):作为最后的捕获分支,当前面所有if
和elif
条件都为False
时执行。- 代码可读性:对于特定已知颜色的情况,使用
elif alien_color == "red":
可能比直接用else:
更明确,但在此练习中,else
暗示了“非绿色且非黄色”的情况。
练习5:人生的不同阶段
设置变量age
的值,再编写一个if-elif-else
结构,根据age
的值判断这个人处于人生的哪个阶段。
- 如果年龄小于2岁,就打印一条消息,指出这个人是婴儿。
- 如果年龄为2(含)~4岁(不含4),就打印一条消息,指出这个人是幼儿。
- 如果年龄为4(含)~13岁(不含13),就打印一条消息,指出这个人是儿童。
- 如果年龄为13(含)~18岁(不含18),就打印一条消息,指出这个人是少年。
- 如果年龄为18(含)~65岁(不含65),就打印一条消息,指出这个人是中青年人。
- 如果年龄达到65岁(含),就打印一条消息,指出这个人是老年人。
age = 25 # 可以修改这个值来测试不同阶段
if age < 2:
print("这是一个婴儿")
elif age < 4: # 隐含 age >= 2
print("这是一个幼儿")
elif age < 13: # 隐含 age >= 4
print("这是一个儿童")
elif age < 18: # 隐含 age >= 13
print("这是一个少年")
elif age < 65: # 隐含 age >= 18
print("这是一个中青年人")
else: # 隐含 age >= 65
print("这是一个老年人")
这是一个中青年人
知识点回顾:
if-elif-else
链:用于根据变量的不同数值范围执行不同的操作。- 条件顺序的重要性:在
if-elif-else
链中,条件的顺序非常关键。因为Python会按顺序评估,一旦某个条件为真,后续的elif
和else
就会被忽略。例如,如果先判断age < 13
再判断age < 2
,那么一个1岁的婴儿也会被错误地归类为儿童。 - 边界条件:注意题目中对年龄区间的“含”与“不含”的描述,并将其正确转换为比较运算符(
<
,<=
,>
,>=
)。
练习6:喜欢的水果
创建一个列表,其中包含你喜欢的水果,再编写一系列独立的if
语句,检查列表中是否包含特定的水果。
- 将该列表命名为
favorite_fruits
,并让其包含三种水果。 - 编写5条
if
语句,每条都检查某种水果是否在列表中。如果是,就打印一条像下面这样的消息。
You really like bananas!
favorite_fruits = ["apple", "banana", "cherry"]
if "apple" in favorite_fruits:
print("You really like apples!")
if "orange" in favorite_fruits: # 这个条件为 False
print("You really like oranges!")
if "banana" in favorite_fruits:
print("You really like bananas!")
if "pear" in favorite_fruits: # 这个条件为 False
print("You really like pears!")
if "cherry" in favorite_fruits:
print("You really like cherries!")
You really like apples!
You really like bananas!
You really like cherries!
知识点回顾:
- 列表创建:使用方括号
[]
和逗号,
创建包含多个字符串元素的列表。 in
成员运算符:用于检查一个元素是否存在于列表中。"apple" in favorite_fruits
会返回True
或False
。- 独立的
if
语句:与if-elif-else
不同,这里每个if
语句都会被独立评估。如果多个条件都为True
,则它们对应的代码块都会执行。
练习7:以特殊方式跟管理员打招呼
创建一个至少包含5个用户名的列表,并且其中一个用户名为'admin'
。想象你要编写代码,在每个用户登录网站后都打印一条问候消息。遍历用户名列表,向每个用户打印一条问候消息。
- 如果用户名为
'admin'
,就打印一条特殊的问候消息,如下所示。
Hello admin, would you like to see a status report?
- 否则,打印一条普通的问候消息,如下所示。
Hello Jaden, thank you for logging in again.
users = ["admin", "eric", "jaden", "carolina", "david"] # 题目要求至少5个用户
for user in users:
if user == "admin":
print("Hello admin, would you like to see a status report?")
else:
print(f"Hello {user.title()}, thank you for logging in again.") # 使用f-string和title()使名字首字母大写
Hello admin, would you like to see a status report?
Hello Eric, thank you for logging in again.
Hello Jaden, thank you for logging in again.
Hello Carolina, thank you for logging in again.
Hello David, thank you for logging in again.
知识点回顾:
for
循环:用于遍历列表users
中的每一个元素(用户名)。if-else
结构在循环中:在每次循环迭代时,根据当前user
的值执行不同的print
语句。- 字符串比较:
user == "admin"
检查当前用户名是否为'admin'
。 - f-string (格式化字符串字面量):一种方便的字符串格式化方法,
f"Hello {user.title()}..."
将变量user
的值(经过.title()
方法处理)嵌入字符串中。 - 字符串方法
.title()
:将字符串中每个单词的首字母转换为大写,其余字母小写。
练习8:处理没有用户的情形
在为练习7编写的程序中,添加一条if
语句,检查用户名列表是否为空。
- 如果为空,就打印如下消息。
We need to find some users!
- 删除列表中的所有用户名,确认将打印正确的消息。
users = ["admin", "eric", "jaden"] # 假设初始有一些用户
# users = [] # 测试列表为空的情况
if users: # 当列表不为空时,users 在布尔上下文中为 True
for user in users:
if user == 'admin':
print('Hello admin, would you like to see a status report?')
else:
print(f'Hello {user.title()}, thank you for logging in again.')
else:
print('We need to find some users!')
print("\n--- Testing with an empty list ---")
users = [] # 删除所有用户
if users:
for user in users:
if user == 'admin':
print('Hello admin, would you like to see a status report?')
else:
print(f'Hello {user.title()}, thank you for logging in again.')
else:
print('We need to find some users!')
Hello admin, would you like to see a status report?
Hello Eric, thank you for logging in again.
Hello Jaden, thank you for logging in again.
--- Testing with an empty list ---
We need to find some users!
知识点回顾:
- 列表的布尔值:在Python中,非空列表在布尔上下文中被视为
True
,而空列表[]
被视为False
。因此,可以直接使用if users:
来检查列表是否为空。 - 条件执行:整个
for
循环(包括其内部的if-else
)仅在users
列表不为空时执行。
练习9:检查用户名
按照下面的说明编写一个程序,模拟网站如何确保每个用户的用户名都独一无二。
- 创建一个至少包含5个用户名的列表,并将其命名为
current_users
。 - 再创建一个包含5个用户名的列表,将其命名为
new_users
,并确保其中有一两个用户名也在列表current_users
中。 - 遍历列表
new_users
,检查其中的每个用户名是否已被使用。如果是,就打印一条消息,指出需要输入别的用户名;否则,打印一条消息,指出这个用户名未被使用。 - 确保比较时不区分大小写。换句话说,如果用户名
'John'
已被使用,应拒绝用户名'JOHN'
。(为此,需要创建列表current_users
的副本,其中包含当前所有用户名的全小写版本。)
current_users = ['eMily', 'James', 'lily', 'john', 'Michael']
new_users = ['jOhn', 'miChael', 'Tom', 'jack', 'rose']
# 创建 current_users 的全小写副本以进行不区分大小写的比较
current_users_lower = [user.lower() for user in current_users]
for new_user in new_users:
if new_user.lower() in current_users_lower:
print(f"Username '{new_user}' is already taken. Please enter a new username.")
else:
print(f"Username '{new_user}' is available.")
Username 'jOhn' is already taken. Please enter a new username.
Username 'miChael' is already taken. Please enter a new username.
Username 'Tom' is available.
Username 'jack' is available.
Username 'rose' is available.
知识点回顾:
- 列表创建和遍历:创建
current_users
和new_users
列表,并使用for
循环遍历new_users
。 - 不区分大小写比较:
- 使用字符串方法
.lower()
将用户名转换为全小写进行比较。 - 为提高效率(避免在内层循环中反复对
current_users
的元素调用.lower()
),先创建current_users
的全小写版本current_users_lower
。
- 使用字符串方法
- 列表推导式:用于构建
current_users_lower
列表。 in
成员运算符:new_user.lower() in current_users_lower
检查转换后的新用户名是否存在于小写当前用户列表中。- f-string:用于清晰地打印提示信息。
练习10:序数
序数表示顺序位置,如1st和2nd。序数大多以th结尾,只有1st、2nd、3rd例外。
- 在一个列表中存储数字1~9。
- 遍历这个列表。
- 在循环中使用一个
if-elif-else
结构,打印每个数字对应的序数。输出内容应为"1st 2nd 3rd 4th 5th 6th 7th 8th 9th"
,每个序数都独占一行。
numbers = list(range(1, 10)) # 使用 range 创建列表 [1, 2, ..., 9]
for number in numbers:
if number == 1:
print(f"{number}st")
elif number == 2:
print(f"{number}nd")
elif number == 3:
print(f"{number}rd")
else:
print(f"{number}th")
1st
2nd
3rd
4th
5th
6th
7th
8th
9th
知识点回顾:
range()
函数与list()
:list(range(1, 10))
创建一个包含整数 1 到 9 的列表。for
循环遍历列表:迭代numbers
列表中的每个数字。if-elif-else
结构:根据数字的特定值 (1, 2, 3) 应用不同的序数后缀 (st
,nd
,rd
),其他所有数字应用通用后缀 (th
)。- f-string:用于将数字和其对应的序数后缀组合成字符串进行打印。