帮我写一个基于python的购物系统,有查看商品,加入购物车,结账等基础功能
时间: 2023-08-28 14:20:14 浏览: 50
好的,我可以帮你写一个简单的基于Python的购物系统,包括查看商品、加入购物车、结账等基础功能。以下是代码实现:
```python
# 商品信息
products = [
{"name": "MacBook Pro", "price": 9999, "stock": 10},
{"name": "iPhone 12", "price": 6999, "stock": 20},
{"name": "iPad Air", "price": 4999, "stock": 30},
{"name": "Apple Watch", "price": 1999, "stock": 40},
{"name": "AirPods Pro", "price": 1499, "stock": 50}
]
# 购物车
cart = []
# 查看商品
def show_products():
print("欢迎来到Apple Store!")
print("商品列表:")
for i, p in enumerate(products):
print(i+1, p["name"], p["price"], "元")
# 加入购物车
def add_to_cart():
index = int(input("请输入要购买的商品编号:"))
count = int(input("请输入购买数量:"))
product = products[index-1]
if product["stock"] < count:
print("库存不足!")
else:
product["stock"] -= count
item = {"product": product, "count": count}
cart.append(item)
print("商品已添加到购物车!")
# 查看购物车
def show_cart():
print("购物车:")
total_price = 0
for item in cart:
product = item["product"]
count = item["count"]
price = product["price"] * count
total_price += price
print(product["name"], product["price"], "元 x", count, "=", price, "元")
print("总价:", total_price, "元")
# 结账
def checkout():
show_cart()
confirm = input("请确认是否结账(Y/N):")
if confirm == "Y":
print("结账成功!")
cart.clear()
else:
print("取消结账!")
# 主函数
def main():
show_products()
while True:
op = input("请输入操作(1-查看商品;2-加入购物车;3-查看购物车;4-结账;5-退出):")
if op == "1":
show_products()
elif op == "2":
add_to_cart()
elif op == "3":
show_cart()
elif op == "4":
checkout()
elif op == "5":
break
else:
print("无效操作!")
if __name__ == "__main__":
main()
```
这个购物系统包含了查看商品、加入购物车、查看购物车、结账等基础功能,可以直接在命令行中运行。注意,这只是一个简单的示例实现,具体实现还需要根据实际需求进行调整和改进。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)