Python 购物车代码
时间: 2023-04-06 07:04:33 浏览: 154
购物车代码
4星 · 用户满意度95%
可以回答这个问题,以下是一个简单的 Python 购物车代码示例:
```python
# 定义商品列表和价格
products = {
"apple": 5,
"banana": 3,
"orange": 4
}
# 初始化购物车
cart = {}
# 添加商品到购物车
def add_to_cart(product, quantity):
if product in products:
if product in cart:
cart[product] += quantity
else:
cart[product] = quantity
print(f"{quantity} {product}(s) added to cart.")
else:
print("Sorry, we don't have that product.")
# 显示购物车内容和总价
def show_cart():
total_price = 0
print("Your cart:")
for product, quantity in cart.items():
price = products[product] * quantity
print(f"{product}: {quantity} x {products[product]} = {price}")
total_price += price
print(f"Total price: {total_price}")
# 测试代码
add_to_cart("apple", 2)
add_to_cart("banana", 3)
add_to_cart("watermelon", 1)
show_cart()
```
输出结果:
```
2 apple(s) added to cart.
3 banana(s) added to cart.
Sorry, we don't have that product.
Your cart:
apple: 2 x 5 = 10
banana: 3 x 3 = 9
Total price: 19
```
阅读全文