学生管理系统python作业代码
时间: 2025-01-07 21:11:30 浏览: 3
### Python 学生管理系统作业示例代码
#### 功能概述
此学生管理系统支持添加、删除、修改和查询学生信息等功能。通过文件操作持久化存储学生数据。
#### 主要功能模块
- 添加学生信息
- 删除学生信息
- 修改学生信息
- 查询学生信息
- 显示所有学生信息
- 统计学生总数
#### 完整代码实现
```python
import os
def save_students(students, filename="students.txt"):
"""保存学生信息到文件"""
with open(filename, 'w', encoding='utf-8') as wfile:
for student in students:
line = f"{student['id']},{student['name']},{student['age']}\n"
wfile.write(line)
def load_students(filename="students.txt"):
"""从文件加载学生信息"""
if not os.path.exists(filename):
return []
with open(filename, 'r', encoding='utf-8') as rfile:
lines = rfile.readlines()
students = [
{
"id": int(line.split(',')[0]),
"name": line.split(',')[1],
"age": int(line.split(',')[2])
}
for line in lines
]
return students
def add_student():
"""添加新学生记录"""
id_ = input("请输入学号:")
name = input("请输入姓名:")
age = input("请输入年龄:")
new_student = {"id": int(id_), "name": name.strip(), "age": int(age)}
all_students.append(new_student)
save_students(all_students)
print(f"成功添加 {new} 条学生信息")
def delete_student():
"""按ID删除指定学生记录"""
del_id = int(input("请输入要删除学生的学号:"))
global all_students
before_len = len(all_students)
all_students = [stu for stu in all_students if stu["id"] != del_id]
after_len = len(all_students)
if (before_len - after_len) > 0:
save_students(all_students)
print(f"已成功删除 ID={del_id} 的学生")
else:
print(f"未找到 ID={del_id} 的学生")
def modify_student():
"""更新现有学生的信息"""
mod_id = int(input("请输入要修改的学生学号:"))
target_stu = None
for i, stu in enumerate(all_students):
if stu["id"] == mod_id:
target_stu = stu
break
if target_stu is None:
print(f"找不到 ID={mod_id} 的学生")
return
update_name = input(f"当前名字是 [{target_stu['name']}], 新的名字是:")
update_age = input(f"当前年龄是 [{target_stu['age']}], 新的年龄是:")
updated_info = {}
if update_name.strip() != '':
updated_info['name'] = update_name.strip()
if update_age.isdigit():
updated_info['age'] = int(update_age)
if bool(updated_info):
index = next((index for (index, d) in enumerate(all_students) if d["id"] == mod_id), -1)
if index >= 0:
all_students[index].update(updated_info)
save_students(all_students)
print(f"成功更新了 ID={mod_id} 的学生信息")
else:
print("未能完成更新")
else:
print("没有任何更改被提交")
def query_student_by_id():
"""根据ID查找特定学生"""
q_id = int(input("请输入要查询的学生学号:"))
found = False
for s in all_students:
if s.get('id') == q_id:
print(s)
found = True
break
if not found:
print(f"没有找到 ID={q_id} 的学生")
def show_all_students():
"""展示所有学生详情"""
if len(all_students) == 0:
print("目前无任何学生信息")
else:
for idx, item in enumerate(all_students, start=1):
print(f"[{idx}] {item}")
def count_total_students():
"""统计并打印总人数"""
num_of_students = len(all_students)
print(f"系统中共有 {num_of_students} 名学生")
if __name__ == '__main__':
menu_options = {
1: ('添加学生', add_student),
2: ('删除学生', delete_student),
3: ('修改学生', modify_student),
4: ('查询学生', query_student_by_id),
5: ('显示所有学生', show_all_students),
6: ('统计学生数量', count_total_students),
7: ('退出程序', exit)
}
all_students = load_students()
while True:
try:
print("\n=== 学生管理系统 ===\n")
for key, value in menu_options.items():
print(f'{key}. {value[0]}')
choice = int(input('\n请选择您想要执行的操作编号:'))
func_to_call = menu_options.get(choice)[1]
if callable(func_to_call):
func_to_call()
elif isinstance(func_to_call, str) and func_to_call.lower().startswith('exit'):
raise SystemExit
else:
print('无效选项,请重新输入')
except ValueError:
print('仅接受数字作为菜单选择,请重试.')
except KeyboardInterrupt:
print('\n\n强制终止请求收到,正在安全关闭...')
break
finally:
pass
```
阅读全文