1 #author F 2 3 import sys 4 5 #list格式存儲商品信息 6 product_list = [ 7 ('Iphone', 5800), 8 ('MacPro', 10000), 9 ('Bike', 888), 10 ('Watch', 2300), 11 ('Coffee', 58), 12 ('Mouse', 158) 13 ] 14 shopping_list = [] 15 salary = input("input your salary:") 16 if salary.isdigit(): 17 salary = int(salary) 18 while True: 19 for index, item in enumerate(product_list):# enumerate:把下標取出 20 print(index, item) 21 user_choose = input("要買什麼呢?") 22 if user_choose.isdigit(): 23 user_choose = int(user_choose) 24 if 0 <= user_choose < len(product_list): 25 p_item = product_list[user_choose] 26 if p_item[1] <= salary:#買得起 27 shopping_list.append(p_item) 28 salary -= p_item[1] 29 print("Added {item} into your cart and your balance is {balance}".format(item=p_item, balance=salary)) 30 else: 31 print("你的餘額只剩下[%s]啦,還買個毛線啊" % salary) 32 else: 33 print("goods do not exists") 34 elif user_choose == 'q': 35 print("------shopping list------") 36 for p in shopping_list: 37 print(p) 38 print("Your current balance:", salary) 39 sys.exit() #不引入sys會報錯 40 else: 41 print("invalid option")