需求:
商品信息都存在json文件中
1、查询商品信息,校验商品是都存在,校验价格是否合法(校验小数)
2、新增商品,校验商品是都存在,校验价格是否合法
3、修改商品,校验商品是都存在,校验价格是否合法
校验个数,价格要大于0,个数为整数
商品信息json文件
{ "car": { "price": 9999999, "num": 100, "color": "black" }, "pen": { "price": "3", "num": "3", "color": "red" } }
实现:
import json def op_data(FILENAME,content=None): #有content写文件,没content读文件 if content: with open(FILENAME,'w',encoding='utf-8') as fw: json.dump(content,fw,ensure_ascii=False,indent=4) else: with open(FILENAME,encoding='utf-8') as fr: return json.load(fr) FILENAME = 'goods.json' goods = op_data(FILENAME) #商品信息转为字典 def good_exit(goodsname): #校验商品是否存在 if goodsname in goods: return True def price_legal(price): #判断价格是否合法 price = str(price) if price.count('.') == 0 and price.isdigit(): if int(price) > 0: #价格非0 return True elif price.count('.') == 1: price_l = price.split('.') if price_l[0].isdigit() and price_l[1].isdigit(): if float(price) > 0: #价格非0 return True return False def input_legal(): #判断输入数量、颜色、价格是否合法,合法写入文件 num = input('请输入商品个数').strip() color = input('请输入商品颜色').strip() price = input('请输入商品价格').strip() if num.isdigit(): if color.isalpha(): if price_legal(price): goods[name] = {'num': num, 'color': color, 'price': price} op_data(FILENAME,goods) return '操作成功' else: return '商品价格输入错误' else: return '商品颜色输入错误' else: return '商品个数输入错误' def query(goodsname): #查询商品信息 if good_exit(goodsname): print('商品%s的信息是%s'%(goodsname,goods[goodsname])) else: print('商品不存在') def add_goods(name): #新增商品 if good_exit(name): print('商品已存在') else: print(input_legal()) def update_good(name): #修改商品 if good_exit(name): print(input_legal()) else: print('商品不存在') for i in range(3): choice = input('请输入您的选择:1.查询商品 2.新增商品 3.修改商品').strip() if choice == '1': name = input('请输入需要查询的商品名称').strip() query(name) elif choice == '2': name = input('请输入需要添加的商品名称').strip() add_goods(name) elif choice == '3': name = input('请输入需要修改的商品名称').strip() update_good(name) else: print('输入的选择有误')