1. 程式人生 > >python(4)- 簡單練習:python實現購物車的優化

python(4)- 簡單練習:python實現購物車的優化

list x11 int 退出 .html htm src keyword 結算

簡單版本,鏈接如下:

http://www.cnblogs.com/c-x-m/p/7819220.html

購物車程序優化題目要求:

1. 用戶退出時打印商品列表時,按以下格式

-------您購買的商品如下------

id 商品 數量 單價 總價

1 iPhone 2 5800 11400

2 coffee 1 30 30

...

總計價格: 11430元

--------end -------------

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 salary=int(input("please input your salary:")) #輸入薪資 product_list=[["iphone", 5888], #定義商品列表 ["coffee",30],
["bike",299], ["vivo x9",2499], ["cake",40], ["book",99]] product_cart={} #定義購物車字典 total_cost= 0 #定義總花銷 while True: #循環打印可購買商品列表及退出提示 print("可購買的商品") for number in range(len(product_list)): product = product_list[number]
print(number,product) print("q","quit") choice=input("輸入你所選擇的商品編號>>:").strip() #輸入選擇的商品編號或退出“q” if choice.isdigit(): #判斷輸入的是否為整數 choice=int(choice) if choice < len(product_list) and choice >= 0: #判斷輸入的數字是否商品編號範圍內 product=product_list[choice] #定義要買的商品列表 if salary -product[1] >=0: #判斷是否買的起 salary-=product[1] #買的起自動結算 print("將商品",product[0],"加入購物車,","你目前還有余額",salary,"元") #輸出當前本次操作信息及余額 if product[0] in product_cart: #判斷購買的商品是否在購物車裏 product_cart[product[0]][1]+=1 #在購物車裏,則商品對應的數量+1 else: #不在購物車裏,則將商品信息,商品單價,數量加入購物車內 product_cart[product[0]]=[product[1],1] print("目前你的購物車",product_cart) else: #買不起則打印當前余額及差的金額。結束本次循環,重新開始循環,打印可購買商品列表及退出提示 print("你目前還有余額", salary, "元,", "還差", product[1] - salary, "元") else: #輸入的數字不在商品編號範圍內,返回上一循環,打印可購買商品列表及退出提示 print("商品不存在!") elif choice== "q": #輸入的不是數字為字符串“q”,打印已購買商品信息及總花銷 print("---------你購買的商品如下---------") print("id","\t","商品","\t","數量","\t","單價","\t","總價") id_counter=1 #定義購買車商品編號 for key in product_cart: print(id_counter,"\t", #依序打印購物車商品編號,商品,數量,單價及總價 key,"\t", product_cart[key][1],"\t\t", product_cart[key][0],"\t", product_cart[key][1]*product_cart[key][0]) id_counter+=1 total_cost+=product_cart[key][1]*product_cart[key][0] #定義總花銷 print("總計價格為",total_cost) print("------------end------------") break #跳出循環 else: #輸入的既不是整數,也不是字符串“q”,提示信息錯誤 print("你輸入的是什麽鬼?")

  


運行程序結果為:
技術分享

技術分享

技術分享

技術分享

python(4)- 簡單練習:python實現購物車的優化