简单的实现购物车功能,还有不到位的地方,加油!!!
要求:
注意:1、商品列表内的嵌套最好使用元组
2、显示产品的序号,可是使用enumerate,或者使用index
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import time 2 goods = [{"huawei":1000},{"apple":10},{"banana":23},{"pen":140},{"wanju":78}, 3 {"book":200},{"taideng":780},{"rou":432},{"zhuozi":653},{"yizi":1244}] 4 5 6 7 buy_goods = [] 8 all_salary = 0 9 info = True 10 #while True: 11 print("".center(6,"="),"欢迎您的到来","".center(6,"=")) 12 13 while info: 14 salary = input("请输入你的工资:") 15 print("".center(26, "=")) 16 if salary.isdigit(): 17 salary = int(salary) 18 while info: 19 num = 1 20 if num <= len(goods): 21 for good in goods: 22 for bal,value in good.items(): 23 print(num, bal," ",value) 24 num += 1 25 print("退出请按q或Q----购买请按Y或y") 26 print("".center(26, "=")) 27 28 bar_num = input("请输入要买的物品的序号:") 29 if bar_num == 'q' or bar_num == 'Q': 30 info = False 31 elif bar_num.isdigit(): 32 bar_num = int(bar_num) 33 if bar_num <= len(goods) and bar_num > 0: 34 for buy_bars,buy_salary in goods[bar_num - 1].items(): 35 if salary >= buy_salary: 36 salary -= buy_salary 37 all_salary += buy_salary 38 buy_goods.append(buy_bars) 39 #break 40 else: 41 print("您的余额不足") 42 time.sleep(2) 43 44 #break 45 46 elif bar_num == 'y' or bar_num == 'Y': 47 print("您购买的货物有:",buy_goods,"共花费:",all_salary,"元") 48 info = False 49 50 else: 51 print("输入错误!!!") 52 53 54 #print(buy_goods) 55 else: 56 print("输入错误,请重新输入!!!") 57 time.sleep(1)