用python實現購物車功能


"""
功能要求:
1.要求用戶輸入自己擁有的總資產,例如:2000
2.顯示商品列表的序號,商品名稱,商品價格,讓用戶根據序號選擇商品,然后加入購物車
例如:
1 電腦 1999
2 鼠標 10
3 游艇 20

3.用戶可以多次購買商品
4.用戶輸入q退出|輸入n結算
5.結算的時候如果商品總額大於總資產,提示賬戶余額不足,否則,購買成功。
goods = [
{"name": "電腦", "price": 1999},
{"name": "鼠標", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
]

"""
goods = [
{"name": "電腦", "price": 1999},
{"name": "鼠標", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998}]

 1 account=int(input("請輸入您的資產:"))
 2 i=0
 3 dic={}
 4 for el in goods:
 5     i+=1
 6     dic.setdefault(str(i)+el["name"],el["price"]) #使用字符串拼接,把序號加到鍵前面
 7 print(dic)
 8 
 9 lst=[] #創建一個列表形式的購物車
10 money=0 #購物車中初始值為0
11 while 1:
12     ret=input("請輸入您要買的東西序號(q退出.n結算):").strip()
13     if ret.isdigit():
14         for el in dic:
15             if ret == el[0]:  #利用切片得到商品序號,判斷用戶輸入的序號是否是商品序號
16               lst.append(el[1:]) #將商品添加到列表中
17               money +=dic[el]  #計算購物車中商品的總價
18               print("購物車中有:%s,消費總額為%s"%([i for i in lst],money))
19 
20     elif ret.upper()=="Q": #執行退出操作
21        print("退出成功!\n余額還有%s"%account)
22        break
23     elif ret.upper()=="N": #執行結算操作
24        blance=account-money #余額 = 資產 - 消費總額
25        if blance <0:
26            print("您的余額不足!!!")
27        else:
28            print("購買成功,花費了%d,余額還剩%s"%(money,blance))
29        break
30     else:
31        print("輸入有誤,請再次輸入!!!")

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM