products = {
"apple": 0.5,
"banana": 0.25,
"orange": 0.4,
"pear": 0.3
}
# 初始化购物车
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("Product not found.")
# 结算购物车
def checkout():
total = 0
print("----- Receipt -----")
for product, quantity in cart.items():
if product in products:
price = products[product]
subtotal = price * quantity
print(f"{product}: {quantity} x ${price} = ${subtotal}")
total += subtotal
print("-------------------")
print(f"Total: ${total}")
print("Thank you for shopping!")
# 示例用法
add_to_cart("apple", float(input("请输入苹果斤数:")))
add_to_cart("banana", float(input("请输入香蕉斤数:")))
add_to_cart("orange", float(input("请输入橙子斤数:")))
checkout()
在这个示例中,我们定义了一个商品清单和对应的价格。然后,通过add_to_cart()
函数将商品添加到购物车,checkout()
函数用于结算购物车并生成收据。
你可以按照自己的需求扩展和定制这个示例,例如添加更多的商品和价格、增加折扣或优惠券等功能。另外,你也可以使用数据库来管理商品信息和购物车数据。有了Python的灵活性,你可以根据实际场景进行定制开发,并结合其他库和工具来实现更复杂的收银程序。