Python實現簡易購物車(未完結)

使用Python完成購物車功能
需求:

  1.讓用戶輸入金額
  2.選擇要購買的商品,加入購物車
  3.當商品的總價超過了你的金額,提示餘額不足
  4.讓用戶輸入N結算,輸入Q退出
goods = [ {'name':'電腦','price':1999}, {'name':'鼠標','price':15}, {'name':'鍵盤','price':30}, {'name':'硬盤','price':399}, {'name':'內存','price':489}, ] fei_yong = 0 shop_car = {} # 鍵 == 列表的索引,值 == 商品數量 money = input("請輸入你的金額:") if money.isdigit(): # 真錢 while 1: for i in range(len(goods)): print(i+1,goods[i]["name"],goods[i]["price"]) # ===================商品展現============================ choose = input("請輸入您要購買的商品(輸入n或者N結算,輸入q或者Q退出):") if choose.isdigit() and 0 < int(choose) <= len(goods): # 讓用戶輸入商品序號並判斷是否是數字以及在不在正常輸入範圍內 int_index = int(choose) - 1 # 經過用戶輸入的內容減一,獲取到goods的索引 if shop_car.get(int_index) == None: shop_car[int_index] = 1 else: shop_car[int_index] += 1 # ================讓用戶把商品加入到購物車中==================== elif choose.upper() == "N": # 結算 for f in shop_car: fei_yong = fei_yong + shop_car[f] * goods[f]["price"] if int(money) - fei_yong >= 0: for k in shop_car: print(f'您購買的商品是{goods[k]["name"]},單價{goods[k]["price"]},數量{shop_car[k]}') else: print("餘額不足") # for i,v in enumerate(shop_car,1): # 枚舉 # print(f'序號:{i},商品:{goods[v]["name"]},數量:{shop_car[v]}') #  # str_del = int(input("請刪除商品對應的序號:")) # shop_car[str_del - 1] = shop_car[str_del - 1] - 1 # if shop_car[str_del - 1] == 0: # shop_car.pop(str_del - 1) elif choose.upper() == "Q": # 退出 print(f"您這次共消費{fei_yong},剩餘餘額{int(money) - fei_yong}") break else: print("輸入有誤,請從新輸入!") else: # 輸入非數字 print("請正確輸入!")

實現了簡易功能,其他功能慢慢完善git

相關文章
相關標籤/搜索