功能要求:
- 要求用户输入总资产,例如:2000
- 显示商品列表,让用户根据序号选择商品,加入购物车
- 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
- 附加:可充值、某商品移除购物
goods = [ {"name": "电脑", "price": 1999}, {"name": "鼠标", "price": 10}, {"name": "游艇", "price": 20}, {"name": "美女", "price": 998}, ]
1 goods = [ 2 {"name": "电脑", "price": 1999}, 3 {"name": "鼠标", "price": 10}, 4 {"name": "游艇", "price": 20}, 5 {"name": "美女", "price": 998}, 6 ] 7 shopping_cart = [] 8 your_asset = int(input('请输入你的总资产: ')) 9 for my_goods in enumerate(goods): 10 index = my_goods[0]#选择商品的序号 11 shopping_list = my_goods[1]#表示选择商品的清单 12 shopping_name = shopping_list['name']#表示选择的商品的名字 13 shopping_price = shopping_list['price'] 14 print(shopping_list,(index,shopping_name,shopping_price)) 15 while True: 16 your_choose = input('请输入你想要购买商品的序号: ').strip() 17 if your_choose.isdigit(): 18 your_choose = int(your_choose) 19 else: 20 print('输入错误,请重新输入') 21 continue 22 if your_choose < len(goods) and your_choose >= 0: 23 my_index = goods[your_choose] 24 my_shopping_name = my_index['name'] 25 my_shopping_price = my_index['price'] 26 else: 27 print('输入错误,请重新输入') 28 continue 29 if int(my_shopping_price) < int(your_asset): 30 shopping_cart.append(my_shopping_name) 31 print(shopping_cart) 32 your_asset = your_asset - my_shopping_price 33 print('你的剩余的金额为%s'%(your_asset)) 34 go_buy = input('是否想继续购买??>>请回答yes或者no: ') 35 if go_buy == 'yes': 36 print('请继续买你心仪的商品吧!') 37 else: 38 for i in shopping_cart: 39 print('你购买的商品是:%s'%(i)) 40 break 41 else: 42 print('你的余额不足!!') 43 shopping_cart.append(my_shopping_name) 44 ans = input('是否要继续充值>>请回答yes或者no: ') 45 if ans == 'yes'.strip(): 46 recharge = input('请输入你所要充值的金额').strip() 47 recharge = int(recharge) 48 your_asset = your_asset + recharge 49 print('您充值后的金额为%s'%(your_asset)) 50 elif ans == 'no'.strip(): 51 print('余额不足') 52 remove_shopping_cart = input('是否要将商品移除购物车>>请回答yes或者no: ') 53 if remove_shopping_cart == 'yes': 54 remove_shopping = input('请输入要移除的商品序号: ').strip() 55 shopping_cart.remove(goods[int(remove_shopping)]['name']) 56 print('您的购物列表如下: ') 57 for j in shopping_cart: 58 print(j) 59 break 60 elif ans == 'no': 61 print('购买失败') 62 break