代码示例
学员管理系统
需求:完成对学员的增删改查
# 先定义一个函数存显示学员信,有需要再调用
def user_info():
print("-"*20)
print("1.添加学员")
print("2.删除学员")
print("3.修改学员")
print("4.查询学员")
print("5.显示所有功能")
print("6.退出系统")
print("-"*20)
# 等待存储所有学员的信息
info = []
# 添加学员功能
def user_add():
"""添加学员函数"""
# 1.用户输入姓名、学号、手机号
user_name = input("请输入你的姓名:")
user_id = input("请输入你的学号:")
user_phonenum = input("请输入你的手机号码:")
# 2.判断是否添加这个学员,如果已经重名则报错,如果无则添加学员
global info
# 2.1 如果info[]里的name已经存在,则报错
for i in info:
if user_name == i["name"]:
print("用户姓名存在")
# 此时retur作用是,退出当前函数,不执行下面代码
return
# 2.2如果输入的姓名不存在,则添加数据:准备空字典,字典新增数据,列表追加字典
info_dict = {}
# 字典新增数据
info_dict["name"] = user_name
info_dict["id"] = user_id
info_dict["phone"] = user_phonenum
# print(info_dict)
# 列表追加字典
info.append(info_dict)
print(info)
def user_delete():
"""删除学员函数"""
# 1.用户输入所要删除的学员姓名
del_name = input("请输入要删除的姓名:")
# 2.判断学员是否存在:存在则删除;不存在则提示
# 2.1声明info是全局变量
global info
# 2.2.遍历列表
for i in info:
# 2.3 判断学员是否存在:存在执行删除列表里面的字典(用户所输入的); 如果不存在则提示用户。加一个break,因为系统不允许重名,删除了一个后面的不需要再遍历
if del_name == i["name"]:
info.remove(i)
break
else:
print("该学员不存在")
print(info)
def user_Gai():
"""修改学员信息"""
# 1.用户输入目标学员姓名
xiu_Gai = input("请输入要修改的学员姓名:")
# 2.检查这个学员是否存在
global info
for i in info:
# 2.1如果存在,修改学员信息
if xiu_Gai == i["name"]:
i["phone"] = input("请输入你要修改的手机号码:")
break
#2.2不存在则报错
else:
print("输入信息不存在")
# 3.需要这个函数时候再调用
print(info)
def user_finename():
"""查找学员信息"""
fine_name = input("请输入查询学员姓名:")
global info
for i in info:
if fine_name == i["name"]:
print("查找的学员信息如下-----")
print(f"该学员的姓名是:{i['name']},学号是:{i['id']},手机号码是:{i['phone']}")
break
else:
print("查无此人···")
def user_all():
"""显示所有学员信息"""
print("姓名\t学号\t手机号")
global info
for i in info:
print(f"{i['name']}\t{i['id']}\t{i['phone']}")
# 1.显示功能界面
while True:
user_info()
user_num = int(input("请输入所需的功能序号:"))
if user_num == 1:
# print("添加")
user_add()
elif user_num == 2:
# print("删除")
user_delete()
elif user_num == 3:
# print("修改")
user_Gai()
elif user_num == 4:
# print("查询")
user_finename()
elif user_num == 5:
# print("显示所有功能")
user_all()
elif user_num == 6:
# print("退出系统")
# 结束while循环用break
over_choose = input("是否退出系统? 1:是 0:否 :")
if over_choose == '1':
break
else:
print("输入功能序号有误")
# 系统需要循环使用,知道用户输出6,才退出系统
# 定义添加学员的函数:
文件备份实例
代码:
old_name = input("请输入你要备份的文件名:")
index = old_name.rfind(".")#从右边往左数,出现的第一个 ' . ' 点
if index > 0:
postfix = old_name[index:]
# new_name = old_name[:index] + '备份' + old_name[index:]
new_name = old_name[:index] + '备份' + postfix
print(new_name)
old_f = open(old_name,'rb')
new_f = open(new_name,'wb')
while True:
con = old_f.read(1024)
if len(con) == 0:
break
new_f.write(con)
old_f.close()
new_f.close()
需要改动修改之处留下宝贵意见!感谢!