1. (简答题) 编写Python程序实现以下功能:从键盘输入若干同学的姓名,保存在字符串列表中;输入某个同学的名字,检索是否已保存在列表中。
# 初始化一个空列表来存储同学的姓名
students = []
# 从键盘输入姓名
while True:
name = input("请输入同学的姓名(输入'结束'来停止):")
if name == '结束':
break
students.append(name)
# 输出已输入的同学姓名
print("已输入的同学姓名:", students)
# 持续进行姓名检索
while True:
search_name = input("请输入要检索的同学姓名(输入'退出'来停止检索):")
if search_name == '退出':
print("退出检索。")
break
# 检索姓名是否在列表中
if search_name in students:
print(f"{search_name} 在列表中。")
else:
print(f"{search_name} 不在列表中。")
2. (简答题) 编写Python程序实现以下功能:使用字典记录多位同学的姓名及对应身高;输入任意同学的姓名,查找并显示所有高于此身高的同学信息。
# Initialize an empty dictionary to store students' names and heights
students = {}
# Input students' names and heights
while True:
name = input("Enter the student's name (type 'end' to stop): ")
if name.lower() == 'end':
break
height = input(f"Enter {name}'s height (in centimeters): ")
# Store the name and height in the dictionary
students[name] = float(height)
# Output the entered student information
print("Entered student information:", students)
# Find students taller than the specified student
while True:
search_name = input("Enter the name of the student to search for (type 'exit' to stop searching): ")
if search_name.lower() == 'exit':
print("Exiting search.")
break
if search_name in students:
search_height = students[search_name]
print(f"{search_name}'s height is {search_height} cm.")
print("The following students are taller than them:")
# Find and print other students taller than the specified student
found = False
for student, height in students.items():
if height > search_height:
print(f"{student}: {height} cm")
found = True
if not found:
print("There are no students taller than this student.\n")
else:
print(f"Student {search_name} not found.\n")