1 #author:leon 2 product_list= [ 3 (‘iphone‘,5800), 4 (‘mac pro‘,9800), 5 (‘bike‘,800), 6 (‘watch‘,6000), 7 (‘coffee‘,31), 8 (‘book‘,120) 9 ] 10 shopping_list= [] 11 salary = input("input your salary:") 12 if salary.isdigit(): 13 salary=int(salary) 14 while True: 15 for item in product_list: 16 print(product_list.index(item),item) #循环打印产品编号和产品列表(产品名加产品价格) 17 user_choice = input("选择买什么>>>>:") 18 if user_choice.isdigit(): #如果是数字成立, 19 user_choice=int(user_choice) #把数字转换成整型int 20 if user_choice<len(product_list) and user_choice>=0: #输入的数字长度必须小于产品列表的长度,#len()取列表长度 21 P_item=product_list[user_choice] #找出数字user_choice代表的值。例:name[1]找出产品 22 if P_item[1] <= salary: #买得起。列表product_list中嵌套了P_item元组。所以P_item[1],表示取出元祖中第二个值,即价格。 23 shopping_list.append(P_item) 24 salary -=P_item[1] 25 print("add %s into your shopping cart ,you current balance is \033[31;1m%s \033[0m"%(P_item,salary)) 26 else: 27 print("\033[32;1m 你的余额不足 %s"%salary) 28 29 30 elif user_choice =="q": 31 print(".....shopping list ...") 32 for p in shopping_list: #循环打印列表 33 print(p) 34 print("your balance %s " %salary) 35 exit() 36 37 38