1. 程式人生 > >購物車程式優化2

購物車程式優化2

 

 

前幾天寫的購物程式碼覺得特別冗餘,而且可操作性不強,很容易出錯,今天做如下簡化,好用多了。

 

 

 1 # -*- coding:utf-8 -*-
 2 # __Author__ : "110"
 3 # date:2018/12/27
 4 salary = 5000
 5 
 6 shop_list = [('iphone',9000),('mac book',10000),('python book',90),('coffee',32),
 7              ('bicycle',1500)]
 8 
 9 money = input("請輸入您的現金總數:
") 10 money = int(money) 11 have_buy_commodity = [] 12 while True: 13 for i, v in enumerate(shop_list, 1): 14 print(i, v) 15 16 query_buy_shop = input("請輸入要購買的商品編號,q[退出]:") 17 18 if query_buy_shop.isdigit(): 19 query_buy_shop = int(query_buy_shop) 20 21 if query_buy_shop >=1 and
query_buy_shop <=5: 22 spend_money = shop_list[query_buy_shop-1] 23 buy_commodity = shop_list[query_buy_shop-1][0] 24 money = money - spend_money[1] 25 26 if money < 0: 27 print("您的餘額不足,無法購買此商品!") 28 print('--------Shop List--------
') 29 print(have_buy_commodity) 30 print('--------------------------') 31 break 32 else: 33 have_buy_commodity.append(buy_commodity) 34 print("您的餘額為%s元!" % money) 35 36 elif query_buy_shop == 'q': 37 print("已退出購物系統!") 38 print("您的餘額為%s元!" % money) 39 print('--------Shop List--------') 40 print(have_buy_commodity) 41 print('--------------------------') 42 break 43 44 else: 45 print("輸入的字元非法,請重新選擇!")

 

程式碼解析: