mirror of
http://47.106.207.27:3000/Jeremy_liu/AI0814_jiaoan_public.git
synced 2026-09-27 05:14:14 +08:00
123 lines
2.6 KiB
Python
123 lines
2.6 KiB
Python
"""
|
||
03 函数版本:学生增删改查
|
||
|
||
相比列表版本:
|
||
1. 数据仍然用列表和字典保存。
|
||
2. 每个功能拆成一个函数。
|
||
3. 主流程只负责显示菜单和分发任务。
|
||
"""
|
||
|
||
students = []
|
||
next_id = 1
|
||
|
||
|
||
def show_menu():
|
||
print("\n====== 学生管理系统:函数版本 ======")
|
||
print("1. 添加学生")
|
||
print("2. 查看所有学生")
|
||
print("3. 查询学生")
|
||
print("4. 修改学生")
|
||
print("5. 删除学生")
|
||
print("0. 退出")
|
||
|
||
|
||
def add_student():
|
||
global next_id
|
||
name = input("姓名:").strip()
|
||
age = input("年龄:").strip()
|
||
phone = input("电话:").strip()
|
||
|
||
student = {
|
||
"id": next_id,
|
||
"name": name,
|
||
"age": age,
|
||
"phone": phone,
|
||
}
|
||
students.append(student)
|
||
next_id += 1
|
||
print("添加成功")
|
||
|
||
|
||
def list_students():
|
||
if not students:
|
||
print("暂无学生")
|
||
return
|
||
|
||
for student in students:
|
||
print(student)
|
||
|
||
|
||
def find_student_by_id(student_id):
|
||
for student in students:
|
||
if str(student["id"]) == str(student_id):
|
||
return student
|
||
return None
|
||
|
||
|
||
def search_student():
|
||
keyword = input("请输入要查询的姓名:").strip()
|
||
result = []
|
||
|
||
for student in students:
|
||
if student["name"] == keyword:
|
||
result.append(student)
|
||
|
||
if not result:
|
||
print("没有找到该学生")
|
||
return
|
||
|
||
for student in result:
|
||
print(student)
|
||
|
||
|
||
def update_student():
|
||
student_id = input("请输入要修改的学生 ID:").strip()
|
||
student = find_student_by_id(student_id)
|
||
|
||
if student is None:
|
||
print("没有找到该学生")
|
||
return
|
||
|
||
student["name"] = input("新姓名:").strip()
|
||
student["age"] = input("新年龄:").strip()
|
||
student["phone"] = input("新电话:").strip()
|
||
print("修改成功")
|
||
|
||
|
||
def delete_student():
|
||
student_id = input("请输入要删除的学生 ID:").strip()
|
||
student = find_student_by_id(student_id)
|
||
|
||
if student is None:
|
||
print("没有找到该学生")
|
||
return
|
||
|
||
students.remove(student)
|
||
print("删除成功")
|
||
|
||
|
||
def main():
|
||
while True:
|
||
show_menu()
|
||
choice = input("请输入操作编号:").strip()
|
||
|
||
if choice == "1":
|
||
add_student()
|
||
elif choice == "2":
|
||
list_students()
|
||
elif choice == "3":
|
||
search_student()
|
||
elif choice == "4":
|
||
update_student()
|
||
elif choice == "5":
|
||
delete_student()
|
||
elif choice == "0":
|
||
print("程序结束")
|
||
break
|
||
else:
|
||
print("输入有误,请重新输入")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|