# 定义添加学生信息的方法 defadd_stu(): global stu_list stu_dict = {} # 定义列表用于存储学生的信息 # 判断学生是否存在 sid = int(input("请输入添加学生的学号:")) for i in stu_list: if i['sid'] == sid: # 说明该学生已经存在 print("该学生已经存在!") break else: # 只有循环正常结束才会执行 name = input("请输入添加学生的姓名:") age = input("请输入添加学生的年龄:") tel = input("请输入添加学生的电话:") # 将用户输入的内容添加到字典中 stu_dict['sid'] = sid stu_dict['name'] = name stu_dict['age'] = age stu_dict['tel'] = tel # 将字典中的值添加到列表中 stu_list.append(stu_dict) print(stu_list)
# 修改学生信息 defmodify_stu(): global stu_list sid = int(input("请输入您要修改学生的学号:")) # 判断该学生信息是否存在 for i in stu_list: if i['sid'] == sid: new_sid = int(input("请输入新的学生学号:")) i['sid'] = new_sid new_name = input("请输入新的学生姓名:") i['name'] = new_name new_age = input("请输入新的学生年龄:") i['age'] = new_age new_tel = input("请输入新的学生电话:") i['tel'] = new_tel print("修改成功!") # cursor.execute('update stu set sid="new_sid" where sid=i["sid"]') break else: # for else 只有在循环正常结束后才会执行 print("抱歉,没有这个学生!")
# 删除学生的信息 defdel_stu(): sid = int(input("请输入要删除学生的学号:")) count = 0 # 判断学生的信息是否存在 for i in stu_list: if i['sid'] == sid: # 执行删除(del是按照元素下标进行删除的,remove是按照元素值进行删除的 del stu_list[count] print("删除成功!") break count += 1 else: # 当循环正常结束时执行else中的语句 print("没有这个学生!")
# 所有学生的信息 defshow_all(): print("学号\t姓名\t年龄\t电话\t") for i in stu_list: print(f"{i['sid']}\t\t{i['name']}\t{i['age']}\t{i['tel']}\t")
# 查询学生信息 defsearch_stu(): sid = int(input("请输入要查询学生的学号: ")) for i in stu_list: if i.get("sid") == sid: print("学号\t姓名\t年龄\t电话\t") print(f"{i['sid']}\t\t{i['name']}\t{i['age']}\t{i['tel']}\t") break else: print("没有查询到该学生的信息!")