python简易购物系统代码
时间: 2023-07-23 20:18:57 浏览: 178
以下是一个简单的Python代码示例,可供参考,用于实现一个简易的购物系统:
```python
# 定义商品和价格
products = {'apple': 1.0, 'banana': 2.0, 'orange': 3.0, 'pear': 4.0}
# 定义购物车
cart = {}
# 定义总价
total_price = 0.0
# 主函数
if __name__ == '__main__':
# 循环读取用户输入
while True:
# 显示可用商品
print('Available products:')
for product, price in products.items():
print(product, '-', price)
# 显示购物车
print('Cart:')
for product, quantity in cart.items():
print(product, '-', quantity)
# 显示总价
print('Total price:', total_price)
# 获取用户输入
action = input('Do you want to add/remove items or checkout? ')
# 处理用户输入
if action == 'add':
# 获取要添加的商品和数量
product = input('Enter product: ')
quantity = int(input('Enter quantity: '))
# 将商品添加到购物车
if product in products:
if product in cart:
cart[product] += quantity
else:
cart[product] = quantity
total_price += products[product] * quantity
else:
print('Product not available')
elif action == 'remove':
# 获取要删除的商品和数量
product = input('Enter product: ')
quantity = int(input('Enter quantity: '))
# 将商品从购物车中删除
if product in cart:
if cart[product] > quantity:
cart[product] -= quantity
total_price -= products[product] * quantity
else:
total_price -= products[product] * cart[product]
del cart[product]
else:
print('Product not in cart')
elif action == 'checkout':
# 显示总价并退出程序
print('Total price:', total_price)
break
else:
# 无效的输入
print('Invalid action')
```
这是一个简单的示例代码,您需要根据您的具体需求进行适当的修改和优化。例如,您可能需要添加更多的商品、实现现金或信用卡支付等功能。