练习小项目:学生成绩管理器
项目目标
用本章学过的知识,写一个命令行小程序,管理若干学生成绩。
功能要求
至少实现以下功能:
- 添加学生成绩
- 查询某个学生成绩
- 修改学生成绩
- 删除学生成绩
- 显示所有学生成绩
- 统计最高分、最低分、平均分
项目实现
def get_grade(score):if score >= 90:return 'A'if score >= 80:return 'B'if score >= 60:return 'C'return 'D'def print_menu():print('\n===== 学生成绩管理器 =====')print('1. 添加成绩')print('2. 查询成绩')print('3. 修改成绩')print('4. 删除成绩')print('5. 显示全部')print('6. 统计信息')print('0. 退出程序')def input_name(prompt):while True:name = input(prompt).strip()if name:return nameprint('姓名不能为空,请重新输入。')def input_score(prompt):while True:raw = input(prompt).strip()try:score = int(raw)except ValueError:print('分数必须是整数,请重新输入。')continueif 0 <= score <= 100:return scoreprint('分数必须在 0 到 100 之间,请重新输入。')def add_score(scores):name = input_name('请输入学生姓名:')if name in scores:print(f'学生 {name} 已存在,不能重复添加。')returnscore = input_score('请输入分数:')scores[name] = scoreprint(f'已添加:{name} -> {score} 分,等级 {get_grade(score)}')def query_score(scores):name = input_name('请输入要查询的学生姓名:')score = scores.get(name)if score is None:print(f'未找到学生 {name}。')returnprint(f'{name} 的成绩是 {score} 分,等级 {get_grade(score)}')def update_score(scores):name = input_name('请输入要修改的学生姓名:')if name not in scores:print(f'未找到学生 {name}。')returnold_score = scores[name]new_score = input_score('请输入新的分数:')scores[name] = new_scoreprint(f'已修改:{name} 的成绩由 {old_score} 分变为 {new_score} 分,'f'等级 {get_grade(new_score)}')def delete_score(scores):name = input_name('请输入要删除的学生姓名:')removed_score = scores.pop(name, None)if removed_score is None:print(f'未找到学生 {name}。')returnprint(f'已删除:{name} -> {removed_score} 分')def show_all(scores):if not scores:print('当前没有学生成绩记录。')returnprint('\n当前全部学生成绩:')print(f'{"姓名":<12}{"分数":<8}等级')print('-' * 28)for name, score in sorted(scores.items(), key=lambda item: item[0]):print(f'{name:<12}{score:<8}{get_grade(score)}')def show_statistics(scores):if not scores:print('当前没有可统计的数据。')returnvalues = list(scores.values())average = sum(values) / len(values)highest_name = max(scores, key=scores.get)lowest_name = min(scores, key=scores.get)grade_set = {get_grade(score) for score in values}print('\n统计信息:')print(f'学生人数:{len(scores)}')print(f'最高分:{highest_name} -> {scores[highest_name]}')print(f'最低分:{lowest_name} -> {scores[lowest_name]}')print(f'平均分:{average:.2f}')print(f'出现过的等级:{", ".join(sorted(grade_set))}')def main():scores = {'Tom': 95,'Bob': 82,'Alice': 67,}actions = {'1': add_score,'2': query_score,'3': update_score,'4': delete_score,'5': show_all,'6': show_statistics,}while True:print_menu()choice = input('请选择操作:').strip()if choice == '0':print('程序已退出,再见。')breakaction = actions.get(choice)if action is None:print('无效选项,请重新输入。')continueaction(scores)if __name__ == '__main__':main()