1 # 功能要求: 2 # 3 # 要求用户输入总资产,例如:2000 4 # 显示商品列表,让用户根据序号选择商品,加入购物车 5 # 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。 6 # 附加:可充值、某商品移除购物车 7 goods = [ 8 {"name": "电脑", "price": 1999}, 9 {"name": "鼠标", "price": 10}, 10 {"name": "游艇", "price": 20}, 11 {"name": "美女", "price": 998}, 12 ] 13 14 15 money = int(input("输入你的金额:")) 16 print("你拥有的金额:",money) 17 18 li = {} #菜篮子 19 for i in goods: 20 print(i["name"], i["price"]) 21 tag = True 22 while tag : 23 cmd = input("请选择要进行的操作:1、购买2、充值3、购物车4、退出") #选择功能 24 if cmd == "1": 25 while tag : 26 buy = input("请选择你要购买的物品:-----q退出") 27 for i in goods: 28 if buy in i["name"] : #判断是否选择商品,将其添加至列表 29 # yu_e = money - int(i["price"]) 30 # 31 # if yu_e < 0 : 32 # print("购买失败,穷") 33 # continue 34 # else: 35 # print("购买成功,余额为:",money) 36 if buy not in li.keys(): #添加如列表中 37 li[buy] = 1 38 print(li) 39 else: 40 li[buy] += 1 41 print(li) 42 continue 43 if buy == "q": 44 break 45 elif cmd == "2": 46 money += int(input("请输入要充值金额:")) 47 print("你拥有的金额为:",money) 48 elif cmd == "3": 49 while tag: 50 cmd1 = input("请选择购物车操作选项:1、移除物品2、结算3、不输入则退出") 51 if cmd1 == "1": 52 for key,value in li: 53 print(key,value) 54 yichu = input("请选择要移除的商品:") 55 if yichu in li.keys() and li[yichu] == 1: #pop删除 菜篮子中的物品 56 li.pop(yichu) 57 elif yichu in li.keys() and li[yichu] > 1: 58 li[yichu] -= 1 59 else: 60 print("不存在物品") 61 62 elif cmd1 == "2": 63 print("结算中————》余额:",money) 64 print(li) 65 for j in goods: 66 for k in li: #循环看菜单中其价格 67 if k in j["name"]: 68 yu_e = money - int(j["price"])*li[k] 69 money = yu_e 70 if yu_e < 0: 71 print("购买失败,穷") 72 continue 73 else: 74 print("购买",li[k],"成功,余额为:",money) 75 li[k] = 0 #使 菜篮子中的物品数量为0 ,用 pop方法 会报错,字典无序,改变后就不能for 了 76 # if buy not in li.keys(): 77 # li[buy] = 1 78 # print(li) 79 # else: 80 # li[buy] += 1 81 # print(li) 82 continue 83 else: 84 break 85 86 elif cmd == "4": 87 print("正在退出购物系统") 88 tag = False 89 else: 90 print("命令有误")
时间: 2024-10-05 04:41:07