商品管理
-
需求:写一个程序,可以对商品进行:添加、修改、删除、查看
import json FILE_NAME = 'goods.json' def read_product(): with open(FILE_NAME,'a+',encoding='utf-8') as fr: fr.seek(0) result = fr.read() if result: return json.loads(result) return {} def write_product(product): with open(FILE_NAME,'w',encoding='utf-8') as fr: json.dump(product,fr,ensure_ascii=False,indent=4) def get_product_name(): for i in range(3): name = input("请输入商品名称:").strip() if name: return name else: print('商品名称不能为空') else: quit("错误次数过多") def show(): name = get_product_name() product = read_product() if name == 'all': print(product) elif product.get(name): print("商品信息是%s"%product.get(name)) else: print('商品不存在!') def delete(): name = get_product_name() product = read_product() if product.get(name): product.pop(name) print("商品已经被删除") write_product(product) else: print('商品不存在!') def check_count(count:str): if count.isdigit(): if int(count)>0: return int(count) #1 #None def check_price(price:str): count = check_count(price) if count: return count else: if price.count('.')==1 and price.replace('.','').isdigit():#判断小数点只有一个,小数点替换成空 return float(price) if float(price)>0 else None #三元表达式,大于0返回,否则返回None def add(): name = get_product_name() price = input("price:").strip() count = input("count:").strip() color = input("color:").strip() price = check_price(price) count = check_count(count) if price and count and color : product = read_product() if product.get(name): print('无法添加') else: d = {"price":price,'count':count,'color':color} product[name] = d print("添加成功!") write_product(product) else: print("价格/数量/颜色不合法") def modify(): name = get_product_name() price = input("price:").strip() count = input("count:").strip() color = input("color:").strip() price = check_price(price) count = check_count(count) if price and count and color : product = read_product() if product.get(name):#商品存在可以修改 d = {"price": price, 'count': count, 'color': color} product[name] = d print("修改成功!") write_product(product) else: print('商品不存在!') else: print("价格/数量/颜色不合法") # choice = input("请输入:1、添加2、修改、3、查看4、删除、other、退出").strip() # if choice == "1": # add() # elif choice == "2": # modify() # elif choice=="3": # show() # elif show()=="4": # delete() # else: # quit() choice = input("请输入:1、添加2、修改、3、查看4、删除、other、退出:").strip() func_map = {'1':add,'2':modify,'3':show,'4':delete} if choice in func_map: #字典循环取的值是key func_map.get(choice)() else: quit("退出程序!")
本文来自博客园,作者:他还在坚持嘛,转载请注明原文链接:他还在坚持嘛 https://www.cnblogs.com/brf-test/p/14617131.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架