列表--购物
程序功能:
1、启动程序后,让用户输入工资,然后打印商品列表
2、允许用户根据商品编号购买商品
3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
4、可随时退出,退出时,打印已购买商品和余额
your_salary = int(input("Please your salary:")) goods = [[1, "IPhone", 5900], [2, "OPPO", 3700], [3, "MI", 1000], [4, "HP COMPUTER", 2000], [5, "MAC", 10000]] favorite_goods = [] print("Number\tGoods\tPrice") for i in goods: print("%s\t%8s\t%5s" % (i[0], i[1], i[2])) print("输入非数字,结束购物跳转付款菜单") while True: goods_number = input("Please choose your favorite goods:") if goods_number.isdigit(): #如果goods_number是数字,强转成int型 goods_number = int(goods_number) else: break if goods_number > len(goods): #输入的编号不存在,跳转到循环开头 print("Goods is not exist.") continue favorite_goods.append(goods[goods_number-1]) #选择的商品加入到购物车列表中 print(goods[goods_number-1][1] + " 已加入到购物车中") total_goods = 0 for i in favorite_goods: #统计购物车价格 total_goods += i[2] if total_goods > your_salary: print("购买的商品总额为 \033[31;1m%s\033[0m,已经超过了您的工资 \033[31;1m%s\033[0m" % (total_goods, your_salary)) delete_last_goods = favorite_goods.pop() print("已为您清掉商品\033[31;1m%s\033[0m" % (delete_last_goods[1])) total_goods -= delete_last_goods[2] #删除最后一个商品的价格 if favorite_goods == []: #favorite_goods列表为空,退出程序 print("购物车为空,程序退出") quit(0) print("您购物车商品如下:") print("Number\tGoods\tPrice") for i in favorite_goods: #打印购物车 print("%s\t%8s\t%5s" % (i[0], i[1], i[2])) print('-'*8) buy_goods = input("Do you sure to buy(b/B) ?") if buy_goods == 'b' or buy_goods == 'B': #购买商品,并显示余额 print("所购商品总价格: \033[31;1m%s\033[0m" %(total_goods)) print("您的工资剩余:\033[31;1m%s\033[0m" % (your_salary-total_goods)) else: print("取消购买购物车的商品") print("购物车总价格: \033[31;1m%s\033[0m" %(total_goods)) print("工资剩余:\033[31;1m%s\033[0m" % (your_salary))