Development of simple management system - taking educational management system as an example

1. Realization effect (video demonstration)

Score management system

2. Brief description of the code

1. **Student and Teacher Classes**: The code defines two classes, `Student` (student) and `Teacher` (teacher), representing the roles of students and teachers respectively.

2. **Login function**: The `login` function is used for user authentication. It reads user information from a file (`users.txt`) and checks the provided credentials. If the login is successful, an instance of the appropriate class (student or teacher) will be created and allow access to the corresponding menu.

3. **Teacher Class**: The `Teacher` class provides the function of managing student performance. Teachers can perform the following operations: - Record student scores - Query student scores - Delete student scores - Modify student scores - Sort student scores according to different criteria - Count student scores

4. **Student class**: The `Student` class provides students with the function of viewing and modifying their own information (such as grades and personal information).

5. **Menu**: Both the `Teacher` and `Student` classes have a `menu` method, which displays a menu of options that the user can select.

3. Detailed code

 MS.py (main program entry)
##调用student和teacher
##登陆,根据用户属性进入学生菜单、教师菜单
from student import Student
from teacher import Teacher


def login():
    id_name = input("请输入你的账号:")
    passwd = input("请输入你的密码:")

    ##验证用户名的密码,假设账号和密码已经存在
    with open('users.txt', 'r') as file:
        lines = file.readlines()
    # print(lines)
    # Lines的类型:列表
    # for line in lines:
    #     tmp = line.split(',')
    ##验证用户名和密码是否正确,如果正确,再判断用户类型,生成相应的类实例
    for each_line in lines:
        temp = each_line.split(',')
        if id_name == temp[1]:
            if passwd != temp[2]:
                print("密码不正确,请再次输入")
            else:
                if temp[3].strip() == '1':
                    Teacher(temp[1].strip())
                else:
                    stu1 = Student(int(temp[0].strip()))
                    print(stu1.info)
        else:
            print("用户名不存在,请重新输入")
    # info = lines[3].split(',')
    # print(info)


if __name__ == '__main__':
    login()

# from student import Student

# stu1 =Student('1002')
# print(stu1.info)
# print(stu1.search_class_info('math'))
####生成实例的写法不同
# import teather
#
# wang = teather.Teacher("Wang")
# print(wang.students)  ##调用类的函数
stu_info.txt
{1001: {'id': 1001, 'name': 'aaa', 'math': 98, 'Python': 89, 'pe': 76, 'sum': 263}, 1002: {'id': 1002, 'name': 'bbb', 'math': 58, 'Python': 67, 'pe': 86, 'sum': 211}, 1003: {'id': 1003, 'name': 'ccc', 'math': 38, 'Python': 26, 'pe': 16, 'sum': 80}}
student.py
# 定义类
class Student:
    info = {}

    def __init__(self, sID):
        print("welcome ", " ", sID)
        # show info
        with open('stu_info.txt', 'r') as file:
            line = file.readline()

        stu_s = eval(line)
        self.info = stu_s[sID]
        self.menu()

    def menu(self):
        # 类内部的函数
        while True:
            print("==========LOGIN MENU==========")
            print("        1 查询自己的成绩")
            print("        2 查询自己的信息")
            print("        3 修改自己的信息")
            print("        0 退出系统")
            print("==============================")
            print(" 说明:通过输入相应数字选择菜单功能")
            print("==============================")
            # 用户输入选择的菜单项,判断需要进入的功能
            option = eval(input("请输入您的选择项:"))
            if option == 0:
                exit()
            elif option == 1:
                print("1 查询自己的成绩")
                self.search_score()
            elif option == 2:
                print("2 查询自己的信息")
                self.search_info()
            elif option == 3:
                print("3 修改自己的信息")
                self.change_info()
            else:
                print("选择错误,请重新输入")

    def search_score(self):
        for i in self.info:
            print(f'{i}:{self.info[i]}')

    def search_info(self):
        global info_1
        info = []
        for line in open('users.txt', 'r'):
            line = line.replace('\n', '')
            line = line.split(',')
            info.append(line)
        for i in info:
            if i[0] == str(self.info["id"]):
                info_1 = i
                print(f'学号:{i[0]}  账号:{i[1]}  密码:{i[2]}')
                break
        return info_1

    def change_info(self):
        a = []
        a = self.search_info()
        while True:
            changed_info = int(input("1.账号2.密码:"))  # 学生只能修改账号和密码
            for i in range(1, 3):
                if i == changed_info:
                    inform = input("输入你要修改的值:")
                    a[changed_info] = inform
            print(a)

            flag = input("是否要继续修改y/n")
            if flag != 'y':
                break

    def search_class_info(self, class_name):
        print(class_name + ":" + str(self.info[class_name]))
        return self.info[class_name]


# st1 = Student("1001")
# st1.search_class_info("math")


if __name__ == "__main__":
    sID = Student(int(input("请输入学号:")))
teacher.py
class Teacher:
    students = {}

    def __init__(self, name):
        print("welcome " + name)
        self.menu()

    def menu(self):
        self.load_info()
        while True:
            print("==========LOGIN MENU==========")
            print("        1 录入学生成绩")
            print("        2 查找学生成绩")
            print("        3 删除学生成绩")
            print("        4 修改学生成绩")
            print("        5 成绩排序")
            print("        6 统计成绩")
            print("        7 显示所有学生成绩")
            print("        0 退出系统")
            print("==============================")
            print(" 说明:通过输入相应数字选择菜单功能")
            print("==============================")
            option = eval(input("请输入您的选择项: "))
            if option == 0:
                exit()
            elif option == 1:
                print("1 录入学生成绩")
                self.input_info(self.students)
                # self.load_info()
                for key, val in self.students.items():
                    print(key, ":", val)
            elif option == 2:
                print("2 查找学生成绩")
                self.search_info()
            elif option == 3:
                print("3 删除学生成绩")
                self.del_info()
            elif option == 4:
                print("4 修改学生成绩")
                self.change_info()
            elif option == 5:
                print("5 成绩排序")
                self.sort_info()
            elif option == 6:
                print("6 统计成绩")
                self.count_info()
            elif option == 7:
                print("7 显示所有学生成绩")
                self.show_info()

    def load_info(self):
        stu = {"id": 1001, "name": "aaa", "math": 98,
               "Python": 89, "pe": 76, "sum": 98 + 89 + 76}
        self.students[1001] = stu

        stu = {"id": 1002, "name": "bbb", "math": 58,
               "Python": 67, "pe": 86, "sum": 58 + 67 + 86}
        self.students[1002] = stu

        stu = {"id": 1003, "name": "ccc", "math": 38,
               "Python": 26, "pe": 16, "sum": 38 + 26 + 16}
        self.students[1003] = stu
        with open('stu_info.txt', 'w') as file:
            file.write(str(self.students))

    def input_info(self, students):
        # students = {}
        flag_1 = 0
        while True:
            info_list = []
            stud_id = int(input("请输入学号"))
            if not stud_id:
                break

            for key in students:
                if stud_id == students[key]["id"]:
                    print("学号重复,录入失败")
                    flag_1 = 1
                    break

            if flag_1 == 1:
                break

            else:
                name = input("请输入名字:")
                math = int(input("请输入数学成绩:"))
                python = int(input("请输入python成绩:"))
                pe = int(input("请输入体育成绩:"))
                stu = {"stu_id": stud_id, "name": name, "math": math, "python": python, "pe": pe}
                self.students[stud_id] = stu
                print("添加成功")

                flag_2 = input("是否继续添加(y/n):")
                if flag_2 != 'y':
                    break
        with open('stu_info.txt', 'w') as file:
            file.write(str(self.students))

    def search_info(self):
        while True:
            search = int(input("按id查输入1;按姓名查输入2:"))
            if search == 1:
                stu_id = int(input("请输入学生学号 : "))
                print("学号     姓名   数学成绩    Python成绩     体育成绩    总成绩")
                print(self.students[stu_id]["id"], "  ", self.students[stu_id]["name"], "    ",
                      self.students[stu_id]["math"], "       ", self.students[stu_id]["Python"], "        ",
                      self.students[stu_id]["pe"], "       ", self.students[stu_id]["sum"])
            else:
                name = input("请输入学生姓名 : ")
                for key, val in self.students.items():
                    if val['name'] == name:
                        print("学号     姓名   数学成绩    Python成绩     体育成绩    总成绩")
                        print(self.students[name]["id"], "  ", self.students[name]["name"], "    ",
                              self.students[name]["math"], "       ", self.students[name]["Python"], "        ",
                              self.students[name]["pe"], "       ", self.students[name]["sum"])
            flag = input("是否继续查询(y/n):")
            if flag != 'y':
                break

    def del_info(self):
        while True:
            del_id = int(input("请输入要删除的学生ID:"))
            if del_id in self.students:
                del self.students[del_id]
                print("该学生已经删除")
                print("学号     姓名   数学成绩    Python成绩     体育成绩    总成绩")
                for remain_id in self.students:
                    print(self.students[remain_id]["id"], "  ", self.students[remain_id]["name"], "    ",
                          self.students[remain_id]["math"], "       ", self.students[remain_id]["Python"], "          ",
                          self.students[remain_id]["pe"], "    ", self.students[remain_id]["sum"])
            else:
                print("输入错误")
            if self.students == {}:
                print("无任何数据信息")
            flag = input("是否继续删除(y/n):")
            if flag != 'y':
                break

    def change_info(self):
        while True:
            change_id = int(input("请输入要修改的学生ID:"))
            if change_id in self.students:
                name = (input("请输入名字 : "))
                math = int(input("请输入数学成绩 : "))
                python = int(input("请输入Python成绩 : "))
                pe = int(input("请输入体育成绩 : "))
                sum = math + python + pe
                stu = {"id": change_id, "name": name, "math": math, "Python": python, "pe": pe,
                       "sum": sum}
                self.students[change_id] = stu
                print("修改成功!")
            else:
                print("未找到学生信息")
            flag = input("是否继续修改其他学生信息?(y/n):")
            if flag != 'y':
                break

    '''def sort_info(self):
        while True:
            sort_way = int(input("请选择排序方式(1.按数学成绩排序,2.按python成绩排序,3.按体育成绩排序):"))
            if sort_way == 1:
                print("ID 姓名 数学 python 体育 总成绩")
                list1 = []
                for i in self.students.values():
                    list1.append(i['math'])
                list1 = sorted(list1)
                for i in list1:
                    for j in self.students.values():
                        k = j["math"]
                        if i == k:
                            for val in j.values():
                                print(val, end="\t")
                            print(j['math'] + j['python'] + j['pe'])
            elif sort_way == 2:
                print("ID 姓名 数学 python 体育 总成绩")
                list1 = []
                for i in self.students.values():
                    list1.append(i['python'])
                list1 = sorted(list1)
                for i in list1:
                    for j in self.students.values():
                        k = j["python"]
                        if i == k:
                            for val in j.values():
                                print(val, end="\t")
                            print(j['math'] + j['python'] + j['pe'])
            else:
                print("ID 姓名 数学 python 体育 总成绩")
                list1 = []
                for i in self.students.values():
                    list1.append(i['pe'])
                list1 = sorted(list1)
                for i in list1:
                    for j in self.students.values():
                        k = j["pe"]
                        if i == k:
                            for val in j.values():
                                print(val, end="\t")
                            print(j['math'] + j['python'] + j['pe'])'''  # 以上代码太长且复杂

    def sort_info(self):
        # 由于按总成绩排序在最后的show-info中已经排序完成,因此在这不对总成绩进行排序
        while True:
            flag = 0
            sort_way_1 = input("请选择排序方式(math.按数学成绩排序,python.按python成绩排序,PE.按体育成绩排序):")
            sort_way_2 = input("请选择排序方式(1.升序,2.降序)")
            if sort_way_2 == 1:
                if sort_way_1 == 'math' or sort_way_1 == 'python' or sort_way_1 == 'PE':
                    after_sort = sorted(self.students.items(), key=lambda x: x[1][sort_way_1], reverse=False)
                    for i in after_sort:
                        print(f'排序后{i}')
                    flag = 1
                if flag == 0:
                    print("输入有误,返回上一步")
                again = input("是否继续排序(y/n):")
                if again != 'y':
                    break
            else:
                if sort_way_1 == 'math' or sort_way_1 == 'python' or sort_way_1 == 'PE':
                    after_sort = sorted(self.students.items(), key=lambda x: x[1][sort_way_1], reverse=True)
                    for i in after_sort:
                        print(f'排序后{i}')
                    flag = 1
                if flag == 0:
                    print("输入有误,返回上一步")
                again = input("是否继续排序(y/n):")
                if again != 'y':
                    break

    def count_info(self):
        global subject
        while True:
            count = int(input("要查看什么分数的统计(1.数学 2.Python 3.体育):"))
            if count == 1:
                subject = 'math'
            if count == 2:
                subject = 'Python'
            if count == 3:
                subject = 'pe'
            num = part1 = part2 = part3 = part4 = part5 = 0
            for stu in self.students:
                if 90 <= self.students[stu][subject] < 100:
                    part1 += 1
                elif 80 <= self.students[stu][subject] < 90:
                    part2 += 1
                elif 70 <= self.students[stu][subject] < 80:
                    part3 += 1
                elif 60 <= self.students[stu][subject] < 70:
                    part4 += 1
                else:
                    part5 += 1
                num += 1
            sub1 = part1 / num * 100
            sub2 = part2 / num * 100
            sub3 = part3 / num * 100
            sub4 = part4 / num * 100
            sub5 = part5 / num * 100
            print(f"{subject} 的成绩统计如下 : ")
            print(f"一共有 {num} 名学生!")
            print(f"90-100分 {part1} 人,占总人数的 {sub1}%")
            print(f"80-90分 {part2} 人,占总人数的 {sub2}%")
            print(f"70-80分 {part3} 人,占总人数的 {sub3}%")
            print(f"60-70分 {part4} 人,占总人数的 {sub4}%")
            print(f"60分以下 {part5} 人,占总人数的 {sub5}%")

            import matplotlib.pyplot as plt
            import numpy as np
            y = np.array([sub1, sub2, sub3, sub4, sub5]) # 定义饼图的标签,标签是列表
            plt.rcParams['font.sans-serif'] = 'SimHei'  # 设置中文显示
            plt.figure(figsize=(6, 6))  # 将画布设定为正方形,则绘制的饼图是正圆

            plt.pie(y,
                    labels=['90-100分', '80-90分', '70-80分', '60-70分', '60分以下'],  # 设置饼图标签
                    colors=['red', 'yellow', 'green', 'cyan', 'pink'],  # 设置饼图颜色
                    explode=(0.01, 0.01, 0.01, 0.01, 0.01),  # 第二部分突出显示,值越大,距离中心越远
                    autopct='%.2f%%',  # 格式化输出百分比
                    )
            plt.title("成绩分析结果")
            plt.show()



            # colors = ['red', 'yellow', 'green', 'cyan', 'pink'],  # 设置饼图颜色
            # explode = [0.01, 0.01, 0.01, 0.01, 0.01, 0.01]  # 设定各项距离圆心n个半径
            # values = [sub1, sub2, sub3, sub4, sub5]
            # plt.pie(values, explode=explode, labels=label, autopct='%1.1f%%')  # 绘制饼图
            # plt.title('成绩分析结果')  # 绘制标题
            # plt.savefig('./成绩分析结果')  # 保存图片
            # plt.show()

            flag = input("是否继续统计(y/n):")
            if flag != 'y':
                break

    def show_info(self):
        while True:
            # 显示所有成绩并按总分排序
            for i in self.students:
                count_sum = 0
                for j in self.students[i]:
                    if j == 'math' or j == 'python' or j == 'pe':
                        count_sum += int(self.students[i][j])
                print(f'{self.students[i]} 的总分为{count_sum}')

            flag = input("是否要继续查看成绩(y/n):")
            if flag != 'y':
                break


# st1 = Student("1001")#生成学生的实例
# st1..search_class_info("math")#调用类中的函数
if __name__ == '__main__':
    teacher_wang = Teacher("Wang")
users.txt
1001,aaa,aaa123,0
1002,bbb,bbb123,0
1003,ccc,ccc123,0
T001,wang,111,1
T002,li,222,1

Guess you like

Origin blog.csdn.net/weixin_64890968/article/details/132112019