python 学生信息管理系统(一)

  • 本篇展示.py里的代码,记录的知识点放到《python 学生信息管理系统(二)》里
  • 代码是跟着b站python_子木的视频敲的,为了方便个人理解,稍做了些修改与统一,尤其是if else(我习惯把可能性小的放前边,以免遗漏,大概是排除法的思想)
'''需求分析:
1,录入学生信息 insert()
2,查找学生信息 search()
3,删除学生信息 delete()
4,修改学生信息 modify()
5,学生成绩排名 sort()
6,统计学生总人数 total()
7,显示全部学生信息 show()
'''
import os
filename = 'stu.txt'

def main():
    while True:
        menu()
        choice = int(input('请选择:'))
        if choice in [0,1,2,3,4,5,6,7]:
            if choice == 0:
                answer = input('确定退出请扣Y,返回请按任意键')
                if answer =='Y' or answer == 'y':
                    print('已退出,感谢使用')
                    break
                else:
                    continue
            elif choice == 1:
                insert()     # 录入学生信息
            elif choice == 2:
                search()     # 查找学生信息
            elif choice == 3:
                delete()     # 删除学生信息
            elif choice == 4:
                modify()     # 修改学生信息
            elif choice == 5:
                sort()       # 学生成绩排名
            elif choice == 6:
                total()      # 统计学生总人数
            elif choice == 7:
                show()       # 显示全部学生信息

def menu():
    print('==================== 学生信息管理系统 =======================')
    print('----------------------- 功能菜单 --------------------------')
    print('\t\t\t\t\t1,录入学生信息 ')
    print('\t\t\t\t\t2,查找学生信息 ')
    print('\t\t\t\t\t3,删除学生信息 ')
    print('\t\t\t\t\t4,修改学生信息 ')
    print('\t\t\t\t\t5,学生成绩排名 ')
    print('\t\t\t\t\t6,统计学生总人数 ')
    print('\t\t\t\t\t7,显示全部学生信息 ')
    print('---------------------------------------------------------')
    print('=========================================================')

'''注意点:
1,一条学生信息本身是字典,所有学生信息存在列表中(方便修改) [{},{},{}]
2,循环录入学生信息 while True
3,每次录入检查是否符合录入标准
4,把录入信息保存到txt中
'''
# 录入学生信息
def insert():
    stu_lst = []
    while True:
        id = input('录入学生ID(eg:0101):')
        if not id:
            break # 从循环while True重来
        name = input('录入学生姓名:')
        if not name:
            break
        # 录入成绩可能出错(eg:不小心输入了字符)
        try:
            chinese = int(input('录入语文成绩:'))
            math = int(input('录入数学成绩:'))
            english = int(input('录入英语成绩:'))
        except:
            print('输入无效,从头输入')
            continue # 从循环while True重来
        # 将录入的学生信息存到字典(why?)
        stu = {'id':id, 'name':name, 'chinese':chinese, 'math':math, 'english':english}
        # 将学生信息纳入列表
        stu_lst.append(stu)
        print('是否继续添加?y/n')
        answer = input()
        if answer =='y' or answer=='Y':
            continue
        else:
            break
    # 保存以上录入的信息
    save(stu_lst)
    print('学生信息录入完毕')
def save(stu_lst):
    # 可能出错:不知原来的信息是否已经存在于文本文件中
    try:
       info = open(filename,'a',encoding='utf-8') # 有文件则追加
    except:
        info = open(filename,'w',encoding='utf-8')
    for item in stu_lst:
        info.write(str(item)+'\n')
    info.close()

'''循环删除逻辑:旧表中的信息移到新表中
while True:
  input目标id,要求输入合法(不空)
      txt文件是否存在      
      1,不存在 ——> print找不到文件 break
      2,存在  
         旧表=读表
         旧表是否有内容:
         1,无 ——> print无内容 break        
         2,有 
           【 旧表中的信息移到新表中(!!!!!!!核心逻辑代码)】
           写新表,把与目标id不同的行写在新表里           
           是否继续删除y/n
print已完成删除操作!
'''
# 删除学生信息(根据id删信息)
def delete():
    print('当前视图:')
    show()
    while True:
        stu_id = input('要删除的学生的ID是:')
        if stu_id:
            flag = False  # 标记是否删除
            if not os.path.exists(filename): # 如果txt文件不存在
                print('文件不存在')
                break
            else:
                with open(filename,'r',encoding='utf-8') as rfile:
                    stu_info = rfile.readlines()
                if not stu_info: # 如果表内容为空
                    print('表空')
                    break
                else:
                    with open(filename,'w',encoding='utf-8') as wfile:
                        d = {}
                        for item in stu_info:
                            d = eval(item) # 将字符串转成字典
                            if d['id'] != stu_id:
                                wfile.write(str(d)+'\n')
                            else:
                                flag = True
                        if flag:
                            print(f'ID为{stu_id}的学生信息已被删除')
                        else:
                            print(f'没找到ID为{stu_id}的学生')
                    print('是否继续删除?y/n')
                    answer = input()
                    if answer=='y' or answer=='Y':
                        continue
                    else:
                        break
    print('已完成删除操作,当前表的视图:')
    show()

'''循环修改:逻辑同删除操作
核心代码微变:把新成绩修改后再写入新表
'''
# 修改学生信息
def modify():
    print('当前视图:')
    show()
    while True:
        stu_id = input('要修改的学生的ID是:')
        if stu_id:
            flag = False  # 标记是否修改
            if not os.path.exists(filename): # 如果txt文件不存在
                print('文件不存在')
                break
            else:
                with open(filename,'r',encoding='utf-8') as rfile:
                    stu_info = rfile.readlines()
                if not stu_info: # 如果表内容为空
                    print('表空')
                    break
                else:
                    with open(filename,'w',encoding='utf-8') as wfile:
                        d = {}
                        for item in stu_info:
                            d = dict(eval(item)) # 将字符串转成字典
                            if d['id'] != stu_id:
                                wfile.write(str(d)+'\n')
                            else:
                                try:
                                    d['name'] = input('请输入姓名:')
                                    d['chinese'] = input('请输入语文成绩:')
                                    d['math'] = input('请输入数学成绩:')
                                    d['english'] = input('请输入英语成绩:')
                                    flag = True
                                except:
                                    print('输入有误,重新输入!')
                                wfile.write(str(d) + '\n')
                        if flag:
                            print(f'ID为{stu_id}的学生信息已被修改')
                        else:
                            print(f'没找到ID为{stu_id}的学生')
                    print('是否继续修改?y/n')
                    answer = input()
                    if answer=='y' or answer=='Y':
                        continue
                    else:
                        break
    print('已完成修改操作,当前表的视图:')
    show()

'''循环查找:逻辑同删除操作
核心:把查询的信息传到查询表中
'''
# 查找学生信息
def search():#是一个查询过程
    query_lst=[]   # 把查询的信息传到查询表中
    while True:
        id=''
        name=''
        if not os.path.exists(filename):
            print('文件不存在')
        else:
            mode=input('按ID查找请输入1,按姓名查找请输入2:')
            if mode=='1':
                id=input('请输入学生ID:')
            elif mode=='2':
                name=input('请输入学生姓名:')
            else:
                print('您的输入有误,请重新输入')
                continue
            with open(filename,'r',encoding='utf-8') as rfile:
                stu_info = rfile.readlines()
                for item in stu_info:
                    d=eval(item)
                    if id!='':
                        if d['id']==id:
                            query_lst.append(d)
                    elif name!='':
                        if d['name']==name:
                            query_lst.append(d)
            #显示查询结果
            show_student(query_lst)
            #情况列表
            query_lst.clear()
            answer=input('是否要继续查询?y/n\n')
            if answer=='y':
                continue
            else:
                break
def show_student(lst): # 显示查询结果
    if len(lst)==0:
        print('没有查询到学生信息,无数据显示!!!')
        return
    # 定义显示格式
    std='{:^6}\t{:^12}\t{:^8}\t{:^8}\t{:^8}\t{:^8}' # 字符串
    print(std.format('ID','姓名','语文成绩','数学成绩','英语成绩','总成绩'))
    for item in lst:
        print(std.format(item.get('id'),
                         item.get('name'),
                         item.get('chinese'),
                         item.get('math'),
                         item.get('english'),
                         int(item.get('chinese'))+int(item.get('math'))+int(item.get('english'))
                         ))

# 显示全部学生信息
def show():
    stu_info = [] # 存学生信息
    if not os.path.exists(filename):
        print('文件不存在')
    else:
        with open(filename,'r',encoding='utf-8') as rfile:
            students = rfile.readlines()
            for item in students:
                stu_info.append(eval(item))
            if not students:
                print('表空')
            else:
                show_student(stu_info)

# 统计学生总人数
def total():
    if not os.path.exists(filename):
        print('文件不存在')
    else:
        with open(filename,'r',encoding='utf-8') as rfile:
            stu_info = rfile.readlines()
            if not stu_info:
                print('表空')
            else:
                print(f'一共有{len(stu_info)}名学生')

'''
选择排序方式,即升序标记为False,降序标记为True
.sort()的参数key结合lambda不太好理解
'''
# 学生成绩排名
def sort():
    show()
    sort_lst = []
    if not os.path.exists(filename):
        print('文件不存在')
    else:
        with open(filename,'r',encoding='utf-8') as rfile:
            stu_info = rfile.readlines()
            if not stu_info:
                print('表空')
            else:
                for item in stu_info:
                    d = eval(item)
                    sort_lst.append(d)
                order = int(input('请选择排序方式(0升序,1降序):'))
                if order==0:
                    order_bool = False
                elif order==1:
                    order_bool = True
                else:
                    print('输入有误,重输。')
                    sort()
                course = int(input('按照什么分排序(0总分,1语文,2数学,3英语):'))
                if course==1:
                    sort_lst.sort(key=lambda x: int(x['chinese']) ,reverse=order_bool)
                elif course==2:
                    sort_lst.sort(key=lambda x: int(x['math']), reverse=order_bool)
                elif course==3:
                    sort_lst.sort(key=lambda x: int(x['english']), reverse=order_bool)
                elif course==0:
                    sort_lst.sort(key=lambda x: int(x['chinese']) + int(x['math']) +int(x['english']), reverse=order_bool)
                else:
                    print('输入有误,重输。')
                    sort()
                show_student(sort_lst)

if __name__ == '__main__':
    main()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值