1 __author__ = 'ZZG' 2 3 ''' 4 程序:购物车 5 需求: 6 1.启动程序,让用户输入工资,然后打印商品列表 7 2.允许用户根据商品编号购买商品 8 3.用户选择商品后,检测余额是否够,足够直接扣款,不够就提醒 9 4.可以随时退出,退出时,打印已购买商品和余额 10 ''' 11 12 commodity = [[1, 'book', 400],[2, 'iphone', 5500], 13 [3, "dell pc", 6000],[4, 'shoe',300]] 14 15 balance = int(input("please enter you sallary?")) 16 shopped_cart = [] 17 18 19 while True: 20 print('shopp list') 21 #打印商品列表 22 23 for i in commodity: 24 print(i) 25 26 goods_number = int(input('please enter nummber of your want to shop goods ')) 27 #购买编号为1的商品 28 if goods_number == commodity[0][0]: 29 if balance > commodity[0][2]: 30 shopped_cart.append(commodity[0]) 31 print("you have shopped following goods:",shopped_cart,"you balance:",balance) 32 continue 33 else: 34 print("your balance not enough",balance) 35 ex = input('do you want to exit,y or n') 36 if ex == "y": 37 break 38 else: 39 continue 40 balance = sallary - commodity[0][2] 41 42 43 #购买编号为2的商品 44 elif goods_number == commodity[1][0]: 45 if balance > commodity[1][2]: 46 shopped_cart.append(commodity[1]) 47 48 print("you have shopped following goods:",shopped_cart) 49 else: 50 print("your balance not enough",balance) 51 ex = input('do you want to exit,y or n') 52 if ex == "y": 53 break 54 else: 55 continue 56 if goods_number == "Back": 57 continue 58 else: 59 print("invilid enter,please input again") 60 balance = balance - commodity[1][2] 61 62 63 # 购买编号为3的商品 64 elif goods_number == commodity[2][0]: 65 if balance > commodity[2][2]: 66 shopped_cart.append(commodity[2]) 67 print("you have shopped following goods:",shopped_cart) 68 else: 69 print("your balance not enough",balance) 70 ex = input('do you want to exit,y or n') 71 if ex == "y": 72 break 73 else: 74 continue 75 if goods_number == "Back": 76 continue 77 else: 78 print("invilid enter,please input again") 79 balance = balance - commodity[2][2] 80 81 82 #购买编号为4的商品 83 elif goods_number == commodity[3][0]: 84 if balance > commodity[3][2]: 85 shopped_cart.append(commodity[3]) 86 print("you have shopped following goods:",shopped_cart) 87 else: 88 print("your balance not enough",balance) 89 ex = input('do you want to exit,y or n') 90 if ex == "y": 91 break 92 else: 93 continue 94 if goods_number == "Back": 95 continue 96 else: 97 print("invilid enter,please input again") 98 balance = balance - commodity[3][2]
这个简单的功能今天折腾了很久,就是这个balance如何在条件语句中可以来回计算,成为全局变量。
每购买一件商品就计算一下余额,并balance加入列表shopped_cart中?