5-1 条件测试 编写一系列条件测试,将每个测试以及对其结果的预测和实 际结果打印出来。
car = 'subaru'
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru') # 输出True
print("\nIs car == 'audi'? I predict False.")
print(car == 'audi') # 输出False
练习 5-5:外星人颜色 3 将练习 5-4 中的 if-else 结构改为 if-elif-else 结构。
- 如果外星人是绿色的,就打印一条消息,指出玩家获得了 5 分。
- 如果外星人是黄色的,就打印一条消息,指出玩家获得了 10 分。
- 如果外星人是红色的,就打印一条消息,指出玩家获得了 15 分。
from random import choice
alien_color = ['green', 'yellow', 'red']
alien_color = choice(alien_color) #返回alien_color的随机项
print(alien_color)
# 如果外星人是绿色的,玩家获得了 5 个点。
# 如果外星人是黄色的,玩家获得了 10 个点。
# 如果外星人是红色的,玩家获得了 15 个点。
if alien_color == 'green':
print('you win 5 points!')
elif alien_color == 'yellow':
print('you win 10 points!')
else:
print('you win 15 points!')
练习 5-10:检查用户名 按下面的说明编写一个程序,模拟网站如何确保每位用户 的用户名都独一无二。
- 创建一个至少包含 5 个用户名的列表,并将其命名为 current_users。
- 再创建一个包含 5 个用户名的列表,将其命名为 new_users,并确保其中有一两 个用户名也包含在列表 current_users 中。
- 遍历列表 new_users,对于其中的每个用户名,都检查它是否已被使用。如果是, 就打印一条消息,指出需要输入别的用户名;否则,打印一条消息,指出这个 用户名未被使用。
- 确保比较时不区分大小写。换句话说,如果用户名'John'已被使用,应拒绝用 户名'JOHN'。(为此,需要创建列表 current_users 的副本,其中包含当前所有 用户名的小写版本。
current_users = ['PERSON1', 'PERSON2', 'PERSON3', 'person4', 'person5'] # 当前用户名的列表
current_users_lower = [current_user.lower() for current_user in current_users] # 转换为小写
print(current_users_lower)
new_users = ['Person2', 'PERSON5', 'person6', 'person7', 'person8'] # 新用户列表
# 遍历列表 new_users,检查它是否已被使用。
for new_user in new_users:
if new_user.lower() in current_users_lower:
print(f"{new_user} has been used!")
else:
print(f"{new_user} has not been used!")