運用迴圈判斷語句和列表的購物車程式
阿新 • • 發佈:2018-11-19
針對迴圈判讀語句和列表的運用練習,對應Day2中的第一個購物車程式訓練。
能力有限,可能存在不足。
1 # Author: JC 2 3 while 1: 4 balance = input("請輸入工資金額:") 5 if balance.isdigit(): 6 balance = int (balance) 7 buy_list = [] 8 goods_list = [[0,'Iphone',6000],[1,'Bike',800],[2,'Computer', 5800],[3,'CoffeeView Code', 49],[4,'Winds', 200]] 9 while True : 10 for i in goods_list : 11 print(i) 12 goods_number = int(input("請輸入需要購買的商品編號:")) 13 #print(int(goods_list [int(goods_number )][-1])) 14 if goods_number < len(goods_list) and goods_number >= 0: #是否為列表中的數字 15 if goods_list [goods_number ][-1] > balance : 16 print("您的餘額只有:{balance}".format(balance = balance )) 17 print("餘額不足夠,請選擇其他商品:") 18 #for i in goods_list: 19 #print(i) 20 else: 21 balance = balance - goods_list [goods_number][-1] 22 buy_list_provisional = goods_list[goods_number] 23 print("購買的商品為:{list_confim}".format(list_confim=buy_list_provisional)) 24 print("所剩餘額為:%s"%balance) 25 buy_list .append(goods_list [goods_number]) 26 buy_confim = input("是否繼續購買:y/n?") 27 if buy_confim == 'y':continue 28 break 29 else:print("請輸入存在的商品編號!") 30 print("已購買商品:") 31 #print(buy_list ) 32 for i in buy_list: 33 print(i) 34 print("使用者餘額為:{_balance}".format(_balance = balance )) 35 break 36 else: 37 print("請輸入金額數字!")
另附,一個比較好點的購物車程式。
1 product_list = [ 2 ('Iphone',5800), 3 ('Mac Pro',9800), 4 ('Bike',800), 5 ('Watch',10600), 6 ('Coffee',31), 7 ('Python',120), 8 ] 9 shopping_list = [] 10 salary = input("Input your salary:") 11 if salary.isdigit():#判斷是否為數字 12 salary = int (salary) 13 14 while True : 15 for index,item in enumerate (product_list) :#下標和列表內容一起列印 16 print(index,item) 17 user_choice = input("選擇購買商品:") 18 if user_choice .isdigit():#是否是數字 19 user_choice = int (user_choice) 20 if user_choice < len(product_list ) and user_choice >= 0:#是否為列表中的數字 21 shopping_car = product_list[user_choice ] 22 if shopping_car [1] <= salary :#買得起 23 shopping_list.append(shopping_car) 24 salary -= shopping_car [1] #扣費 25 print("Add %s into shopping car,your current balance is \033[31;1m%s\033[0m."%(shopping_car ,salary)) 26 #凸顯色彩輸出格式 27 else: 28 print("\033[23;1m你的餘額只剩[%s]啦,還買個毛線啊!\033[0m"%salary ) 29 else: 30 print("Product code [%s] is not exist!"%user_choice) 31 print("Please choice production again:") 32 elif user_choice == 'q': 33 print("--------shopping list--------") 34 for p in shopping_list : 35 print(p) 36 print("Your current balance:",salary ) 37 exit() 38 else: 39 print("invalid option") 40 else: 41 print("Please enter number...")View Code