1. 程式人生 > >python-購物車程式練習

python-購物車程式練習

 

購物車練習題:
需求如下
1、啟動程式後,讓客戶輸入自己的金額,並打印出商品列表
2、讓客戶根據商品編號,選擇商品
3、選擇完成後,檢測餘額是否夠,夠就直接扣款並將商品儲存至字典中,如果餘額不足提示使用者進行充值
4、使用者可以隨時選擇退出,退出時列印自己購買的商品 ,消費總額和餘額

product_list = [
  ["臺式電腦", 4992],
  ["手機", 2999],
  ["行動硬碟", 390],
  ["U盤", 100],
  ["筆記本", 6223],
  ["滑鼠", 200],
  ["鍵盤", 492]
]
####################################################
product_list = [["臺式電腦", 4992],["手機", 2999], ["行動硬碟", 390],["U盤", 100], ["筆記本", 6223],["滑鼠", 200], ["鍵盤", 492]]

shopping = {}
bbb= 0
# sho = {
# "臺式電腦":{"price":4992,"num":3}
# }
salary = input("請輸入您的工資:")
if salary.isdigit():
salary = int(salary)
while True:
# for i in product_list:
# print(product_list.index(i),i)
for a, b in enumerate(product_list):
print(a, b)
user_choice = input("選擇要買的商品序列(q/Q結算):")

if user_choice.isdigit(): # 判斷輸入的是否是數字
user_choice = int(user_choice) # 將str數字轉為int型別
if user_choice < len(product_list) and user_choice >= 0: # 判斷數字時候是列表序列的範圍
# 判斷錢夠不夠
p_item = product_list[user_choice] # 這個是一個商品["臺式電腦", 4992]
if p_item[1] <= salary: # 判斷商品列表中的價格和你的工資的關係

if p_item[0] in shopping.keys():
shopping[p_item[0]]["num"] += 1
salary -= p_item[1] # 將工資總數減去你選的商品的價格
print(shopping)
print("Added %s into shopping cart, yu e is %s" % (p_item, salary))
else:
shopping[p_item[0]] = {"price":p_item[1],"num":1} # 如果是你工資大於等於商品價格,則將商品加入到shopping空列表中
salary -= p_item[1] # 將工資總數減去你選的商品的價格
print("Added %s into shopping cart, yu e is %s" %(p_item,salary))
print(shopping)
else:
print("資產不足,請充值:當前商品價格為:%s ,您資產剩餘為: %s"%(p_item,salary))
chong = input("充值請輸入c,結算請輸入q,輸入其他字元為無效")
if chong == "c":
b = input("請輸入您要充值的金額:")
if b.isdigit():
b = int(b)
salary += b
print("您充值資產為:%s ,當前資產為 %s ,購物車列表為:%s" %(b,salary,shopping))
continue
elif chong == "q":
print("您購買的商品有:%s ,您的資產剩餘 %s" % (shopping, salary))
for k, v in shopping.items():
n = v["price"]
m = v["num"]
zong = n * m
bbb = bbb + zong
print("總消費為: %s" % (bbb))
#for k,v in cat.items():
# print(k,v)
# n = v['num']
# m = v['one_proce']
# all_sum = n * m
# all_price = all_price + all_sum
exit()
else:
continue
else:
print("請輸入正確的商品序號")
elif user_choice.lower() == "q":
print("您購買的商品有:%s ,您的資產剩餘 %s" %(shopping,salary))
for k,v in shopping.items():
n = v["price"]
m = v["num"]
zong = n * m
bbb = bbb + zong
print("總消費為: %s" %(bbb))
exit()
else:
print("請輸入正確的商品序號")