初学Python第一个小项目,学生管理系统(无数据库)

概要

实训选的是人工智能,要使用Python,然而没学过,本项目是实训课的第一个项目,用Python做一个简单的学生管理系统,无对象属性要求。因为之前一直在学Web后端,第一感觉就是使用MVC架构。然而初学Python不会用数据库且实验室的电脑没装C++ runtime 2019 ,直接存txt里了。

文件结构

在这里插入图片描述

代码

视图层(View)

menu.py

实现前后端分离、虽然不是B/S架构,view层只负责显示,不服则数据和检验和计算

import controller

#统一回复的复用
def isOK(resp):
    if resp['ok']:
        print('执行成功')
    else:
        print('执行失败,原因:%s' %resp['msg'])

#主菜单
def menu():
    f = open('./View/menu.txt','r',encoding='utf-8')
    temp = f.read()
    f.close()
    print(temp)
    sel = input('请输入功能选择:')


    while sel not in ['6']:

        if sel  in ['1','2','3','4','5']:
            seli = int(sel)
        #功能选择
        #1添加学生
            if seli ==1:
                name,id,age,sex = input('请输入学生姓名、学号、年龄、性别(英文逗号隔开):').split(',')
                resp= controller.addStu(name,id,age,sex)
                isOK(resp)
                sel=input('请输入功能选择:')
        #2删除学生
            elif seli ==2:
                name,id = input('请输入被删除学生的姓名学号(英文逗号分割):').split(',')
                resp = controller.remStu(name,id)
                isOK(resp)
                sel = input('请输入功能选择:')
        #3修改信息
            elif seli ==3:
                name, id, age, sex = input('请输入学生姓名、学号、年龄、性别(英文逗号隔开,不可修改学号):').split(',')
                resp= controller.chaStu(name, id, int(age), sex)
                isOK(resp)
                sel = input('请输入功能选择:')
        #4
            elif seli ==4:
                id = input('请输入查询id:')
                resp = controller.seaStu(id)
                isOK(resp)
                #stu为None时print会报错
                if resp['data'] :
                    print('姓名:%s-学号:%s-年龄:%d-性别:%s' %(resp['data']['name'],resp['data']['id'],resp['data']['age'],resp['data']['sex']))
                sel = input('请输入功能选择:')
        # 5
            elif seli ==5:
                resp=controller.listStu()
                # print(resp['data'])
                isOK(resp)
                # print(type(resp['ok']))
                for l in resp['data']:
                    print(l)
                sel = input('请输入功能选择:')
        # # 6
        #     elif seli ==6:
        #         pass
        else:
            sel = input('输入错误,请重新输入(只能输入1-6):')

menu.txt

----------------
|1.添加学生     |
----------------
|2.删除学生     |
----------------
|3.修改学生     |
----------------
|4.查询学生     |
----------------
|5.显示所有学生 |
----------------
|6.退出系统     |
----------------

控制器(Controller)

controller.py

封装了统一的回复函数respone,定义了各类数据检验的函数,以及被View层调用的函数(B/S架构中API)

import model
#添加学生
def addStu(name,id,age,sex):
    _,ok,_ = seaStu(id)
    if ok:
        return False,respone(2,None)
    # 存在判断与性别输入判断
    if not ageCheck(age):
        return  False,respone(1,None)

    if not sexCheck(sex):
        return Falsem,respone(4,None)


    newStu =model.stu(name,id,age,sex)
    f = open('./Data/Data.txt','a')
    f.write('%s,%s,%d,%s\n' %(newStu.getName(),newStu.getId(),newStu.getAge(),newStu.getSex()))
    f.close()
    return respone(0,_)

#删除学生
def remStu(name,id):
    f = open('./Data/Data.txt', 'r',encoding='utf-8')
    # temp =f.readlines()
    ok = False

    lines = f.readlines()
    f.close()
    # print(lines)

    f_w = open('./Data/Data.txt', 'w',encoding='utf-8')

    for line in lines:
        temp = line.split(',')
        # print(temp)
        if name in temp and id in temp:
                #当找到对象时,ok变为True
                ok = True
                continue
        f_w.write(line)

    f_w.close()
    if not ok :
        return respone(3,None)
    else:
        return respone(0,None)

# 修改学生
def chaStu(name,id,age,sex):
    ok = False
    f = open('./Data/Data.txt', 'r',encoding='utf-8')
    # temp =f.readlines()
    lines = f.readlines()
    f.close()
    # print(lines)

    f_w = open('./Data/Data.txt', 'w',encoding='utf-8')

    for line in lines:
        temp = line.split(',')
        # print(temp)
        if id in temp:
            f_w.write('%s,%s,%d,%s\n'%(name,id,age,sex))
            #修改成功时,ok变为True
            ok = True
            continue
        # print(line)

        f_w.write(line)
    f.close()
    if not ok:
        return respone(3,None)
    else:
        return respone(0,None)

#查询学生
def seaStu(id):
    f = open('./Data/Data.txt', 'r', encoding='utf-8')

    lines = f.readlines()
    f.close()
    for line in lines:
        temp=line.split(',')
        if id in temp:
            # print(line)
            stu = model.stu(str(temp[0]), str(temp[1]), int(temp[2]), str(temp[3])[:-1])
            # break
            return respone(0,stu.getStu())
    # stu = model.stu(str(temp[0]),str(temp[1]),int(temp[2]),str(temp[3])[:-1]))
    return respone(3,None)


#显示所有学生
def listStu():
    f = open('./Data/Data.txt', 'r', encoding='utf-8')
    lines = f.readlines()
    f.close()
    list =[]
    for line in lines:
        temp = line.split(',')
        list.append('姓名:%s-学号:%s-年龄-%d-性别:%s' %(str(temp[0]),str(temp[1]),int(temp[2]),str(temp[3])[:-1]))
        # print('姓名:%s-学号:%s-年龄-%d-性别:%s' %(str(temp[0]),str(temp[1]),int(temp[2]),str(temp[3])[:-1]))
        # print(temp)
        # print(line)
    return respone(0,list)



#年龄检测
def ageCheck(age):
    if age not in [str[i] for i in range(1,101)]:
        return False

#性别输入检测
def sexCheck(sex):

    if sex not in ['boy', 'girl']:
        return False

#0表示成功 1表示年龄输入不合规行 2表示学生已存在 3表示查找不到学生 4表示性别输入错误
def respone(n,data):
    if n == 0:
        msg = 'success'
    if n == 1:
        msg =  '年龄输入不合规行'
    if n == 2:
        msg = '学生已存在'
    if n == 3:
        msg =  '查找不到学生'
    if n == 4:
        msg ='性别输入错误'
    return {
            'msg':msg,
            'ok':(True if (n==0) else False),
            'data':data
        }

模型(Model)

model.py

我这个项目做的一个缺陷时把本该是model层的从存储功能写到了Controller层中了,在实验室的时候因为不懂Python语法,一直上网查一路用注释调试一股脑写下去了,写完才发现把存储写到了Controller层中了,Model层有点成为花瓶,而且不熟悉Python中类的使用,照猫画虎。

"""
虽然好像并没有怎么用到的Model层
一不小心把Model层的函数写Controller里了

"""

import bson

class stu:
    def __init__(self,name, id ,age,sex):
        self.name = name
        self.id = id
        self.age = age
        self.sex = sex
        

    def getId(self):
        return self.id

    def getName(self):
        return self.name

    def getAge(self):
        return self.age

    def getSex(self):
        return self.sex

    def getStu(self):
         return {'name':self.name,'id':self.id,'age':self.age,'sex':self.sex}




主函数

main.py

主要是为了打包成exe

#version 1.0
#空指针报错?
#version 1.1
#因为python初学,不会用异常处理,尽量用if,else避免报错
#version 1.2
#让每一层各司其职,view层只负责显示,controller层提供reasful接口

import View.menu
def main():
    View.menu.menu()
if __name__ == '__main__':
    main()



Pyinstaller

安装

pip install pyinstaller

使用
控制台切到main.py目录,执行:

pyinstalle main.py

生成exe文件在dist目录中,把main.exe剪切黏贴到项目更目录中在控制台中输入main就可使用(把源码删除也没问题)
在这里插入图片描述

可改进的地方

  • 文件读取使用的时readlines如果几个G的数据全挤在一行估计内存会炸
  • 数据更新使用的时文件的按行重写,数据多时效率低
  • 打算用bson文件进行存储,一个对象一个bson文件
  • 把存储封装到Moedel层,在Controller层只需要调用(倒不如说这本来就是Model层做的)
  • 异常处理还不会用,if else很多很多
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值