自己写的垃圾版本:
1 # Author:yebo 2 3 4 items = [ 5 [1,"iphone",5800], 6 [2,"mac pro",12000], 7 [3,"latte",31], 8 [4,"python start",81], 9 [5,"bike",800] 10 ] 11 shopping_list = [] 12 13 my_salary = int(input("my salary:")) 14 15 while True: 16 print(items) 17 items_number = int(input("which one do you want to buy?")) 18 items_index = items_number - 1 #实际列表排序从0开始 19 20 if items[items_index][2] > my_salary: 21 print("you don not have enough money") 22 else: 23 my_salary = my_salary - items[items_index][2] 24 print("you have bought %s,which is %d, my salary remain:%d" 25 %(items[items_index][1],items[items_index][2],my_salary)) 26 shopping_list.append(items[items_index][1]) 27 28 continue_confirm = input("if you want to quit, please press 'q'; if not, please press any key.") 29 if continue_confirm == "q": 30 break 31 32 print("***----list----***") 33 print("you have bought:") 34 for i in shopping_list: 35 print(i) 36 print("***------------***")
老男孩Alex老师版本:
1 __author__ = "Alex Li" 2 3 4 product_list = [ 5 ('Iphone',5800), 6 ('Mac Pro',9800), 7 ('Bike',800), 8 ('Watch',10600), 9 ('Coffee',31), 10 ('Alex Python',120), 11 ] 12 shopping_list = [] 13 salary = input("Input your salary:") 14 if salary.isdigit(): #判断输入是否是数字 15 salary = int(salary) 16 while True: 17 for index,item in enumerate(product_list): #方法一:enumerate在同时需要index和value的时候使用 18 #print(product_list.index(item),item) #方法二:用.index增加了商品编号 19 print(index,item) 20 user_choice = input("选择要买嘛?>>>:") 21 if user_choice.isdigit(): #判断输入是否是数字 22 user_choice = int(user_choice) 23 if 0 <= user_choice < len(product_list): #len()直接得到列表长度 24 p_item = product_list[user_choice] #取出购买的商品 25 if p_item[1] <= salary: #买的起 26 shopping_list.append(p_item) #增加到购物车 27 salary -= p_item[1] 28 print("Added %s into shopping cart,your current balance is \033[31;1m%s\033[0m" %(p_item,salary) ) 29 else: 30 print("\033[41;1m你的余额只剩[%s]啦,还买个毛线\033[0m" % salary) #增加字体颜色 31 else: 32 print("product code [%s] is not exist!"% user_choice) 33 elif user_choice == 'q': 34 print("--------shopping list------") 35 for p in shopping_list: 36 print(p) 37 print("Your current balance:",salary) 38 exit() 39 else: 40 print("invalid option")