#商品管理的程序 ,商品都存在一个json串# 1新增商品 校验商品是否存在 校验价格是否合法# 2查询商品信息 校验商品是否存在# 3修改商品信息 校验商品是否存在#4 删除import jsonFILE_NAME ='goods.json'def op_file(name,content=None): if content: with open(name,'w',encoding='utf-8')as fw: #写 json.dump(content,fw,indent=4,ensure_ascii=False) else: with open(name,encoding='utf-8')as fr: #读 res = json.load(fr) return resall_goods = op_file(FILE_NAME)def check_price(price): #校验价格 price = str(price) if price.isdigit(): price = int(price) if price>0: return True else: if price.count('.')==1: tmp = price.split('.') left = tmp[0] right = tmp[1] if left.isdigit() and right.isdigit()and int(right)>0: #1.0 return True elif left.isdigit() and right.isdigit()and int(left)>0: #0.1 return True return Falsedef get_good_info(): #商品信息 while True: good_name = input('请输入商品名称:').strip() price = input('请输入商品价格:').strip() count = input('请输入商品数量:').strip() color = input('请输入商品颜色:').strip() if good_name and price and count and color: if not check_price(price): print('价格输入不合法,必须大于0') elif not count.isdigit and int(count)<1: print('商品数量不合法') else: return good_name,price,count,color else: print('输入不能为空!')def add_good(): #添加商品 good_name,price,count,color = get_good_info() if good_name not in all_goods: all_goods[good_name]={ 'price':price, 'count':count, 'color':color } op_file(FILE_NAME,all_goods) print('添加完成!') else: print('商品已经存在!')def update_good(): #修改商品 good_name,price,count,color = get_good_info() if good_name in all_goods: all_goods[good_name]={ 'price':price, 'count':count, 'color':color } op_file(FILE_NAME,all_goods) print('修改完成!') else: print('商品不存在!')def query_good(): #查询 good_name = input('请输入商品名称:').strip() if good_name in all_goods(): print(all_goods.get(good_name)) else: print('商品不存在')def delete_good(): #删除 good_name = input('请输入商品名称:').strip() if good_name in all_goods: all_goods.pop(good_name) op_file(FILE_NAME,all_goods) else: print('商品不存在')def main(): for i in range(3): choice = input('请输入你的选择' '1.添加' '2.修改' '3.删除' '4.查看' '5.退出') if choice =='1': add_good() elif choice =='2': update_good() elif choice =='3': delete_good() elif choice =='4': query_good() elif choice =='5': quit('程序退出') else: print('输入错误,请重新输入!') return main()main()