Python---student management system (pyinstaller)

Column: python
Personal homepage: HaiFan.
Column introduction: This column mainly updates some basic knowledge of python, and also implements some small games, address book, class time management system and so on. Interested friends can pay attention to it.


foreword

Features

  1. new student
  2. show students
  3. find students
  4. delete student
  5. save to document

insert image description here


Create entry function

In the entry function, you can print a menu first, and use the menu to interact.

def menu():
    print('1.新增学生')
    print('2.显示学生')
    print('3.查找学生')
    print('4.删除学生')
    print('0.退出程序')

The menu alone is not enough, because the number entered corresponds to the option on the menu. So you can create an input and return value in the menu, return the input value, and use a variable to receive it.

def menu():
    print('1.新增学生')
    print('2.显示学生')
    print('3.查找学生')
    print('4.删除学生')
    print('0.退出程序')
    choice = input('请输入您的选择:')
    return choice

Correspond to the content that needs to be realized according to the options in the menu.
This can be done with if-else-elifstatements.

ret = menu()
        if ret == '1':
            #新增学生
            insert()
        elif ret == '2':
            #显示学生
            show()
        elif ret == '3':
            #查找学生
            find()
        elif ret == '4':
            #删除学生
            del()
        elif ret == '0':
            #退出程序
            print('bye bye')
            sys.exit(0)
        else:
            print("输入错误,请重新输入")

When adjusting the student information, it is necessary to make multiple changes, so the above code should be placed in the loop, and when the user is finished, enter the specified number or other things before exiting. When the input is wrong, let the user re-enter.

    while True:
        #通过menu函数来打印除菜单
        ret = menu()
        if ret == '1':
            #新增学生
            insert()
        elif ret == '2':
            #显示学生
            show()
        elif ret == '3':
            #查找学生
            find()
        elif ret == '4':
            #删除学生
            delete()
        elif ret == '0':
            #退出程序
            print('bye bye')
            sys.exit(0)
        else:
            print("输入错误,请重新输入")
            #进入下次循环,让用户重新输入
            continue

In this way, the general framework of the student management system. Next, implement the function corresponding to the option.

insert image description here
When you finish the framework, you can consider running it for a try.

New student insert

To add a new student, you must first enter the basic information of the student. Here, you can get a list of global variables and a dictionary of local variables. Why? Because with a dictionary, all the information of the students can be stored in it, and then each element of the list is a dictionary, and each dictionary is a student.

def insert():
    StuId = input('请输入学生的学号:')
    StuName = input('请输入学生的姓名:')
    StuGender = input('请输入学生的性别:')
    if StuGender not in ('男','女'):
        print('性别输入不符合的内容不符合要求')
        return
    StuClass = input('请输入学生的班级:')

    #使用一个字典把上述信息给聚合起来

    StuDict = {
    
    
        'StuId':StuId,
        'StuName':StuName,
        'StuGender':StuGender,
        'StuClass':StuClass
    }

    global StuList
    StuList.append(StuDict)
    print('新增学生完毕')

insert image description here
Here, it is impossible to see whether the newly added students are in the list, so showthe function to display students will be implemented below.

show students show

Show students just need to traverse the students

def show():
    #遍历全局变量的这个列表,把每个学生的信息给打印出来。
    print(f'[{
      
      ["StuId"]}]\t{
      
      ["StuName"]}\t{
      
      ["StuGender"]}\t{
      
      ["StuClass"]}')
    for stu in StuList:
        print(f'[{
      
      stu["StuId"]}]\t\t\t{
      
      stu["StuName"]}\t\t\t{
      
      stu["StuGender"]}\t\t\t\t{
      
      stu["StuClass"]}')
    print(f'显示学生完毕!共有{
      
      len(StuList)}个学生')

Because variables are stored in memory, when the program ends, the data in memory will be destroyed, so you need to re-enter the information every time you run the program.
To solve this problem, I will store the data in a file in a moment.

insert image description here

find studentsfind

The function of finding students, here, take the name search as an example.
First enter the student's name, and then start traversing the global variable StuListto see if there is a matching student. If there is: print out the matching student's information, if not: continue traversing until the traversal is complete, flag依旧为False, it will output that no matching student with the name is found matching classmates.

def find():
    name = input('请输入要查找的同学的姓名')
    cnt = 0
    flag = False
    print(f'[{
      
      ["StuId"]}]\t{
      
      ["StuName"]}\t{
      
      ["StuGender"]}\t{
      
      ["StuClass"]}')
    for stu in StuList:
        if name == stu['StuName']:
            print(f'[{
      
      stu["StuId"]}]\t\t\t{
      
      stu["StuName"]}\t\t\t{
      
      stu["StuGender"]}\t\t\t\t{
      
      stu["StuClass"]}')
            cnt += 1
            flag = True
    if not flag:
        print(f'没有找到与该姓名相匹配的同学')
    print(f'查找到了{
      
      cnt}个匹配的同学')

insert image description here

delete student delete

Deleting a student by name is similar to finding a student by name, first enter the student's name, and then traverse the global variables

def delete():
    name = input('请输入要删除学生的姓名')
    flag = False
    #看看这个要函数学生的姓名对应列表中的哪个元素,把这个元素删除了就好
    for stu in StuList:
        if name == stu['StuName']:
            StuList.remove(stu)
            flag = True
    if not flag:
        print('没有找到该学生,请重新查找')
        res = input('若不进行删除,则输入1,退出删除程序,输入其他则重新删除学生')
        if res == '1':
           pass
        else:
            delete()
    #删除之后学生的人数为
    print(f'删除之后学生的人数为{
      
      len(StuList)}')

insert image description here

Join the archive to read the file

The agreement file is placed in the D:/FileOperator/Stu.txt file
and the student information is saved in the form of line text Student
ID\ tName\tGender\tClass Student ID\tName\tGender\tClassStudent ID\
t
Name\tgender\tclass
Each student occupies one line.
Use \t tabs to separate the information of each student

archive

Archiving is to add student content to a file. This operation is a traversal, and students can be added each time.

def save():
    """
    用于存档
    """

    with open('d:/FileOperator/Stu.txt','w',encoding = 'UTF8') as f:
        for s in StuList:
            f.write(f"{
      
      s['StuId']}\t{
      
      s['StuName']}\t{
      
      s['StuGender']}\t{
      
      s['StuClass']}\n")
        print(f'存档成功,共存储了{
      
      len(StuList)}个记录')

insert image description here
But there is only an archive, and every time it is run, the students are displayed, but there is still no record of adding students before. This is because the added students are in the file and have not been written into the memory.

read file

The strip method can remove blanks at the beginning and end of a string.
Blanks are spaces, newlines, carriage returns, tabs, etc.

os.path.exists This is used to detect whether the file exists, open the file in 'r' mode, if the file does not exist, an exception will be thrown.
clear is used to clear the list.

To read the file, you must first check the file to see if the file exists, then traverse the content in the file, and write the content of the file into a dictionary, because a dictionary is an element in a list, and an element is a student . As we said before, the content in the file is \tdivided by 4. After removing the blanks, it can be splitused to split the characters. After the split, the split string list is returned, because the content of the student is only four, so We can use an element to receive the return value of split, and judge whether there are 4 elements, and make an abnormal judgment on this.

def load():
    """
    读档
    """
    # 若文件不存在,则直接跳过读档流程
    #为了避免读方式打开文件,文件不存在造成的抛出异常
    if not os.path.exists('d:/FileOperator/Stu.txt'):
        return
    global StuList
    StuList.clear()
    with open('d:/FileOperator/Stu.txt','r',encoding = 'UTF8') as f:
        for line in f:
            #针对这一行的数据,按照\t进行切分操作
            #却分之前,取到文件里的换行
            line = line.strip()
            tokens = line.split('\t')
            if len(tokens) != 4:
                print(f'当前行格式有问题! line = {
      
      line}')
                continue
            StuDict = {
    
    
                'StuId':tokens[0],
                'StuName':tokens[1],
                'StuGender':tokens[2],
                'StuClass':tokens[3]
            }

            StuList.append(StuDict)
    print('读档成功')

insert image description here
insert image description here

Packaged into an exe program for release

First open the terminal,

insert image description here
Then enter and pip install pyinstallerpress Enter, and the download will begin.
When entering
pyinstaller -F StudentManagementSystem.py StudentManagementSystem.pythis name, I am naming this file, and this name is the name of the file to be packaged.

insert image description here

A lot of things will come out after that, don't bother with him, and finally a file will appear in the directory dist, click to open it and it will be the file to be packaged.

insert image description here
insert image description here
insert image description here
You can also use the student management system by clicking this exe file.

In this way, this program can be copied to other machines for use, and it can be run without a Python environment.

the code

"""
    学生管理系统
    珍惜在学校的时间。
"""



import sys

import os

#使用这个全局变量,来管理所有学生的信息
#表的每一个元素都是字典,每一个字典就是一个同学
StuList = []

def save():
    """
    用于存档
    """

    with open('d:/FileOperator/Stu.txt','w',encoding = 'UTF8') as f:
        for s in StuList:
            f.write(f"{
      
      s['StuId']}\t{
      
      s['StuName']}\t{
      
      s['StuGender']}\t{
      
      s['StuClass']}\n")
        print(f'存档成功,共存储了{
      
      len(StuList)}个记录')

def load():
    """
    读档
    """
    # 若文件不存在,则直接跳过读档流程
    #为了避免读方式打开文件,文件不存在造成的抛出异常
    if not os.path.exists('d:/FileOperator/Stu.txt'):
        return
    global StuList
    StuList.clear()
    with open('d:/FileOperator/Stu.txt','r',encoding = 'UTF8') as f:
        for line in f:
            #针对这一行的数据,按照\t进行切分操作
            #却分之前,取到文件里的换行
            line = line.strip()
            tokens = line.split('\t')
            if len(tokens) != 4:
                print(f'当前行格式有问题! line = {
      
      line}')
                continue
            StuDict = {
    
    
                'StuId':tokens[0],
                'StuName':tokens[1],
                'StuGender':tokens[2],
                'StuClass':tokens[3]
            }

            StuList.append(StuDict)
    print('读档成功')

def menu():
    print('1.新增学生')
    print('2.显示学生')
    print('3.查找学生')
    print('4.删除学生')
    print('0.退出程序')
    choice = input('请输入您的选择:')
    return choice

def insert():
    StuId = input('请输入学生的学号:')
    StuName = input('请输入学生的姓名:')
    StuGender = input('请输入学生的性别:')
    if StuGender not in ('男','女'):
        print('性别输入不符合的内容不符合要求')
        return
    StuClass = input('请输入学生的班级:')

    #使用一个字典把上述信息给聚合起来

    StuDict = {
    
    
        'StuId':StuId,
        'StuName':StuName,
        'StuGender':StuGender,
        'StuClass':StuClass
    }

    global StuList
    StuList.append(StuDict)
    save()
    print('新增学生完毕')


def show():
    #遍历全局变量的这个列表,把每个学生的信息给打印出来。
    print(f'[{
      
      ["StuId"]}]\t{
      
      ["StuName"]}\t{
      
      ["StuGender"]}\t{
      
      ["StuClass"]}')
    for stu in StuList:
        print(f'[{
      
      stu["StuId"]}]\t\t\t{
      
      stu["StuName"]}\t\t\t{
      
      stu["StuGender"]}\t\t\t\t{
      
      stu["StuClass"]}')
    print(f'显示学生完毕!共有{
      
      len(StuList)}个学生')

def find():
    name = input('请输入要查找的同学的姓名')
    cnt = 0
    flag = False
    print(f'[{
      
      ["StuId"]}]\t{
      
      ["StuName"]}\t{
      
      ["StuGender"]}\t{
      
      ["StuClass"]}')
    for stu in StuList:
        if name == stu['StuName']:
            print(f'[{
      
      stu["StuId"]}]\t\t\t{
      
      stu["StuName"]}\t\t\t{
      
      stu["StuGender"]}\t\t\t\t{
      
      stu["StuClass"]}')
            cnt += 1
            flag = True
    if not flag:
        print(f'没有找到与该姓名相匹配的同学')
    print(f'查找到了{
      
      cnt}个匹配的同学')

def delete():
    name = input('请输入要删除学生的姓名')
    flag = False
    #看看这个要函数学生的姓名对应列表中的哪个元素,把这个元素删除了就好
    for stu in StuList:
        if name == stu['StuName']:
            StuList.remove(stu)
            flag = True
    if not flag:
        print('没有找到该学生,请重新查找')
        res = input('若不进行删除,则输入1,退出删除程序,输入其他则重新删除学生')
        if res == '1':
           pass
        else:
            delete()
    save()
    #删除之后学生的人数为
    print(f'删除之后学生的人数为{
      
      len(StuList)}')

def main():
    """
    入口函数
    """
    #通过控制台和用户进行交互
    print('----------------------------------------')
    print('|         欢迎来到学生管理系统             |')
    print('----------------------------------------')
    load()
    while True:
        #通过menu函数来打印除菜单
        ret = menu()
        if ret == '1':
            #新增学生
            insert()
        elif ret == '2':
            #显示学生
            show()
        elif ret == '3':
            #查找学生
            find()
        elif ret == '4':
            #删除学生
            delete()
        elif ret == '0':
            #退出程序
            print('bye bye')
            sys.exit(0)
        else:
            print("输入错误,请重新输入")
            #进入下次循环,让用户重新输入
            continue

main()

Guess you like

Origin blog.csdn.net/weixin_73888239/article/details/128770588