购物车
# 功能要求:
# 要求用户输入总资产,例如:2000
# 显示商品列表,让用户根据序号选择商品,加入购物车
# 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
# 附加:可充值、某商品移除购物车
goods=[{"name":"电脑","price":1999},
{"name":"鼠标","price":10},
{"name":"游艇","price":20},
{"name":"美女","price":998},
]
shopping_cart=[]
flag=True
sum=0
while flag:
money=input("请输入您的账户金额:").strip()
if money.isdigit():
money=int(money)
print("商品列表:")
while flag:
for i in range(len(goods)):
print(i+1,goods[i]["name"],goods[i]["price"])
choice=input("请选择您需要购买的商品或退出(q):").strip()
if choice.isdigit():
choice=int(choice)
choice=choice-1
if choice >=0 and choice <len(goods):
if money > goods[choice]['price']:
product=goods[choice]
if product in shopping_cart:
n_cart = [cart for cart in shopping_cart if cart["name"] == product["name"]][0]
n_num = n_cart.get("num")
n_cart["num"] += 1
else:
product["num"] = 1
shopping_cart.append(product)
money = money - goods[choice ]["price"]
sum+=goods[choice ]["price"]
print("购买成功,您购买了"+goods[choice]['name'],'您还剩'+str(money)+'元钱')
elif money<goods[choice]['price']:
print("对不起,您的账户余额不足!")
flag=False
else:
print('商品不存在')
continue
elif choice.lower()=='q':
print('---购物清单---')
print("编号 商品 价格 数量")
for cart in shopping_cart:
print(str(shopping_cart.index(cart)+1) +" " +str(cart["name"]) + " " + str(cart["price"]) + " " + str(cart.get("num", 0)))
print('共消费'+str(sum)+'元'+'
您的余额是'+str(money)+'元'+'
---结束购物---')
flag=False
else:
print('请输入数字或q')
continue
else:
print('请输入数字')