本次编写的是实时购买(输入商品直接进行购买),余额不足可以进行充值或结束购物
1 goods = [ 2 {"name": "电脑", "price": 1999}, 3 {"name": "鼠标", "price": 10}, 4 {"name": "游艇", "price": 20}, 5 {"name": "美女", "price": 998}, 6 ] 7 gouwuche = {} 8 xiaofei = 0 9 zongxiaofei = 0 10 for buy_list in goods: 11 gouwuche[buy_list["name"]] = {"num":0, "jiage":buy_list["price"]} 12 zichan = int(input("请输入资产:")) 13 print("--------------shangpin list--------------") 14 for shangpin_list in goods: 15 print(shangpin_list["name"], shangpin_list["price"]) 16 print("-------------------end-------------------") 17 while True: 18 print("您的当前余额为:", zichan) 19 buy_name = input("输入商品名称进行购买:") 20 if buy_name in gouwuche.keys(): 21 if zichan >= gouwuche[buy_name]["jiage"]: 22 gouwuche[buy_name]["num"] = gouwuche[buy_name]["num"] + 1 23 print("购买成功! ") 24 else: 25 print("余额不足,还差:", gouwuche[buy_name]["jiage"] - zichan) 26 chongzhi = input("请输入'y'or'Y'前往充值或者输入'n'or'N'结束购物:") 27 if chongzhi.lower() == "y": 28 jine = int(input("请输入充值金额:")) 29 zichan = zichan + jine 30 print("充值成功! ") 31 continue 32 elif chongzhi.lower() == "n": 33 print("您本次购物结束,结余:", zichan, "总消费:", zongxiaofei) 34 exit() 35 else: 36 print("商品不存在,重新输入:") 37 continue 38 for jiesuan_key, jiesuan_values in gouwuche.items(): 39 jiesuan_num = jiesuan_values["num"] 40 jiesuan_jiage = jiesuan_values["jiage"] 41 xiaofei = jiesuan_num * jiesuan_jiage 42 zichan = zichan - xiaofei 43 zongxiaofei = zongxiaofei + xiaofei 44 gouwuche[buy_name]["num"] = gouwuche[buy_name]["num"] - 1