python列表及循环语句综合练习——简单模拟购物车
1 # -*- coding: utf-8 -*- 2 3 ''' 4 ------------------------------------------------ 5 假设:加入购物车即扣款 6 问题描述:非int型输入值输入,无法使代码不报错,输出至报错 7 解决方案:isdigit()判断输入合法性 8 状态:已解决 9 ------------------------------------------------ 10 ''' 11 12 salary = input("请输入你的工资:") 13 if salary.isdigit(): 14 commodity_msg_list = ['none', '1. iphone6s ¥5800', '2. mac book ¥9000', '3. coffee ¥32', '4. python book ¥80', '5. bicycle ¥1500'] 15 commodity_price = [0, 5800, 9000, 32, 80, 1500] 16 commodity_bought = [] 17 buy_times = 1 18 while buy_times > 0: 19 commodity_msg = ''' 20 欢迎来到本店! 21 22 本店有如下商品: 23 1. iphone6s ¥5800 24 2. mac book ¥9000 25 3. coffee ¥32 26 4. python book ¥80 27 5. bicyle ¥1500 ''' 28 print(commodity_msg) 29 bianhao = [0, 1, 2, 3, 4, 5] 30 commodity_bianhao = input("请输入您想购买的商品编号:\n") 31 if commodity_bianhao.isdigit(): 32 if int(commodity_bianhao) in bianhao: 33 if commodity_price[bianhao[int(commodity_bianhao)]] > int(salary): 34 chajia = int(salary) - commodity_price[bianhao[int(commodity_bianhao)]] 35 print("余额不足,差¥%d!" % chajia) 36 buy_times += 1 37 else: 38 chajia = int(salary) - commodity_price[bianhao[int(commodity_bianhao)]] 39 print("已加入购物车,您的余额为:\n¥%d" % chajia) 40 commodity_bought.append(str(commodity_msg_list[bianhao[int(commodity_bianhao)]])) 41 print("您的购物车中已有以下商品:") 42 print(str(commodity_bought)) 43 salary = int(chajia) 44 buy_times += 1 45 else: 46 print("对不起,输入错误,没有您需要的商品,请重新输入!") 47 buy_times += 1 48 else: 49 print("invalid input!") 50 buy_times += 1 51 end_buy = input("退出购买请输入q,继续购买请输入c:\n") 52 if end_buy == "q": 53 if len(commodity_bought) == 0: 54 cq = input('''您尚未购买任何商品!\n输入c再看看 or 输入q结束:''') 55 if cq == "q": 56 print("谢谢您的光临,欢迎下次再来!") 57 break 58 else: 59 buy_times += 1 60 else: 61 print("谢谢您的光临,欢迎下次再来!") 62 break 63 buy_times += 1 64 else: 65 print("invalid input!")
不乱于心,不困于情,不畏将来,不念过往,如此安好!