请设计实现一个商城系统开发v2.0【代码优化】
1 #!/usr/bin/env python 优化的部分:1.改用字典取键,来调用函数【原来是用if-else判断】 【补充】:也可以用列表,按索引取,可以在列表最前面加一个“”任意元素,凑成一个。就和缩影对上了 2 # -*- coding:utf-8 -*-
2.直接return 不再 return func(),这样写不好,返回值是None。改完以后 return 执行直接跳回while循环
3.返回上一级改成 用if 判断 + continue 增加了输入其他内容报 “输入有误” 3 def goods_list(): 所有函数功能调用都在父级函数下的while循环里调用的 4 ''' 5 # 查看商品列表 6 :return: 7 ''' 8 print("欢迎使用老子的购物商城【商品管理】【查看商品列表】".center(30, "*")) 9 with open("goods.txt",mode="r",encoding="utf-8")as file: #读取所有商品 10 content=file.read() 11 content=content.strip().split("\n") 12 total_lengh=len(content) 13 # 分页展示 14 pages,remainder=divmod(total_lengh,10) 15 if remainder>0: 16 pages+=1 17 while True: 18 option=input("请输入要看的页数(输入N返回上一级:):") 19 if option.upper() == "N": 20 return 21 if int(option)<0 or int(option)>pages: 22 print("页码不输入有误") 23 continue 24 x=(int(option)-1)*10 25 y=int(option)*10 26 print("这是第%s页"%option) 27 for i in content[x:y]: 28 print(i) 29 30 def goods_search(): 31 ''' 32 # 根据关键字模糊搜索指定商品 33 34 :return: 35 ''' 36 37 print("欢迎使用老子的购物商城【商品管理】【根据关键字搜索】".center(30, "*")) 38 with open("goods.txt", mode="r", encoding="utf-8")as file: 39 content = file.read() 40 content_list = content.strip().split("\n") 41 while True: 42 key_word = input("请输入要查询的关键字(输入N返回上一级:):") 43 for i in content_list: 44 if key_word in i: 45 print(i) 46 if key_word.upper() == "N": 47 return 48 def goods_record(): 49 ''' 50 # 录入商品 51 :return: 52 ''' 53 print("欢迎使用老子的购物商城【商品管理】【录入商品】".center(30, "*")) 54 while True: 55 info = [] 56 with open("goods.txt", mode="a", encoding="utf-8")as file: 57 good_name = input("请输入商品名称(输入N返回上一级:):") 58 if good_name.upper() =="N": 59 return 60 info.append(good_name) 61 good_price = input("请输入商品价格):") 62 info.append(good_price) 63 good_count= input("请输入商品数量:") 64 info.append(good_count) 65 file.write(" ".join(info)+"\n") 66 print("添加成功") 67 68 def goods_manage(): 69 ''' 70 查看商品管理目录 71 :return: 72 ''' 73 goods_manage_list={"1":goods_list,"2":goods_search,"3":goods_record,"N":function_list} 74 while True: 75 print("欢迎使用老子的购物商城【商品管理】".center(30, "*")) 76 print(''' 77 1.查看商品列表 78 2.根据关键字搜索指定商品 79 3.录入商品 80 ''') 81 num1=input("请选择(输入N返回上一级:)") 82 if not goods_manage_list.get(num1): 83 print("输入有误,请重新输入") 84 continue 85 goods_manage_list.get(num1)() #调用功能 结束以后 继续返回执行 while循环 86 87 88 89 def vip_manage(): 90 ''' 91 #会员管理 92 :return: 93 ''' 94 95 print("功能正在开发中哦,亲。请重新选择\n") 96 97 98 99 def function_list(): 100 ''' 101 #总功能列表 102 :return: 103 ''' 104 function_list_dict={"1":goods_manage,"2":vip_manage,"N":function_list,'e':exit} #输入 e 直接退出程序 105 while True: 106 print("欢迎使用老子的购物商城".center(30, "*")) 107 print(" 1.商品管理 2.会员管理(不可选,正在开发中)") 108 num=input("请选择(输入N返回上一级:)") 109 if not function_list_dict.get(num): 110 print("输入有误,请重新输入") 111 continue 112 function_list_dict.get(num)() 113 114 function_list()