实现一个商品管理的一个程序,
运行程序有三个选项,输入1添加商品;输入2删除商品;输入3 查看商品信息
1、添加商品:
商品名称:xx 商品如果已经存在,提示商品已存在
商品价格:xx数量只能为大于0的整数
商品数量:xx,数量只能是大于0的整数
2、删除商品:
输入商品名称 ,就把商品删掉
输入输入的商品名称不存在,要提示不存在
3、查看所有的商品
输入商品名称,查出对应价格、数量
输入all 打印出所有的商品信息
输入的商品不存在提示商品不存在
def函数、文件操作、json与字典的转换
python学习笔记(五):python中json与字典格式转换
product_file = ‘product_file.json‘ import json # 读取文件并转换成字典 def read_goods(): with open(product_file,‘a+‘,encoding=‘utf-8‘) as f:#打开文件 f.seek(0) contend=f.read()#读取文件 if len(contend):#判断长度的 if不为空 rf=json.loads(contend) # 这里必须取出数据转成dict格式 否则后续添加商品有问题 return rf else: return {} # 增加商品 def add_good(): good=input(‘请输入商品名称:‘).strip() count=input(‘请输入商品数量:‘).strip() price=input(‘请输入商品价格:‘).strip() all=read_goods() if good==‘‘: print(‘商品名称不能为空‘) elif good in all: print(‘商品已经存在‘) elif int(count)<=0: print(‘商品数量为大于0的整数‘) elif int(price)<=0: print(‘商品价格为大于0的整数‘) else: all[good]={‘price‘:price,‘count‘:count}#将商品加入到字典中 with open (product_file,‘w‘,encoding=‘utf-8‘) as f: #写操作 json.dump(all,f,indent=4,ensure_ascii=False)# 这句代码牛牛再讲一下吧 # 查看商品 def show_good(): all=read_goods() s_good=input(‘请输入要查看的商品名称‘).strip() if s_good in all: s_price=all[s_good][‘price‘] s_count=all[s_good][‘count‘] print(‘商品名称:%s\n商品价格:%s\n商品数量:%s‘%(s_good,s_price,s_count)) elif s_good==‘all‘: print(all) # 删除商品 def del_good(): all=read_goods() d_good=input(‘请输入要删除的商品名称:‘).strip() if d_good in all: all.pop(d_good) with open(product_file,‘w‘,encoding=‘utf-8‘)as f: json.dump(all,f,indent=4,ensure_ascii=False) print(‘已将商品 %s 成功删除‘%d_good) choice=input(‘请选择您的操作:\n1、添加商品\n2、删除商品\n3、查看商品‘) if choice==‘1‘: add_good() elif choice==‘2‘: del_good() elif choice==‘3‘: show_good() else: print(‘输入有误‘)
原文:https://www.cnblogs.com/haifeima/p/9595583.html