购物车程序优化2
前几天写的购物代码觉得特别冗余,而且可操作性不强,很容易出错,今天做如下简化,好用多了。
1 # -*- coding:utf-8 -*- 2 # __Author__ : "110" 3 # date:2018/12/27 4 salary = 5000 5 6 shop_list = [('iphone',9000),('mac book',10000),('python book',90),('coffee',32), 7 ('bicycle',1500)] 8 9 money = input("请输入您的现金总数:") 10 money = int(money) 11 have_buy_commodity = [] 12 while True: 13 for i, v in enumerate(shop_list, 1): 14 print(i, v) 15 16 query_buy_shop = input("请输入要购买的商品编号,q[退出]:") 17 18 if query_buy_shop.isdigit(): 19 query_buy_shop = int(query_buy_shop) 20 21 if query_buy_shop >=1 and query_buy_shop <=5: 22 spend_money = shop_list[query_buy_shop-1] 23 buy_commodity = shop_list[query_buy_shop-1][0] 24 money = money - spend_money[1] 25 26 if money < 0: 27 print("您的余额不足,无法购买此商品!") 28 print('--------Shop List--------') 29 print(have_buy_commodity) 30 print('--------------------------') 31 break 32 else: 33 have_buy_commodity.append(buy_commodity) 34 print("您的余额为%s元!" % money) 35 36 elif query_buy_shop == 'q': 37 print("已退出购物系统!") 38 print("您的余额为%s元!" % money) 39 print('--------Shop List--------') 40 print(have_buy_commodity) 41 print('--------------------------') 42 break 43 44 else: 45 print("输入的字符非法,请重新选择!")
代码解析: