#author devilf product_list = [ ('iphone',5800), ('Mac Pro',9800), ('Bike',800), ('Watch',10000), ('Coffee',123) ] shop_list = [] salary = input('pls enter your salary: ') if salary.isdigit(): #判斷是否爲整形,不然會退出 salary = int(salary) while True: for index,info in enumerate(product_list): #打印列表 # print(product_list.index(info),info) print(index,info) user_choice = input('pls enter what you buy\n>>>: ') #輸入要購買的商品 編號 if user_choice.isdigit(): #再判斷下輸入的是不是數字,不然退出 user_choice = int(user_choice) if user_choice <= len(product_list) and user_choice >= 0: #判斷輸入的編號是否在商品列表的編號範圍內 p_item = product_list[user_choice] #取出編號對應的商品名稱 if p_item[1] <= salary: #判斷改商品的價格是否在工資範圍內 shop_list.append(p_item) #若是在工資範圍內,購買! salary -= p_item[1] #總工資便會減小對應的錢 print('Added %s into shopping cart,your current balance is %s' %(p_item,salary)) else: print('your current balance is %s ,now is not enough' % (salary)) else: print('product %s is not exist!' % user_choice ) elif user_choice == 'q': #若是輸入的是 'q',便會退出 print('-------------shopping list------------') for p in shop_list: print(p) print('quit.....,your current money: ',salary) exit() else: print('Invalid option')