Python 实现商场周年庆购物打折活动
使用 Python 实现商场周年庆购物打折活动
本文将介绍使用 Python 代码实现一个简单的商场周年庆购物打折活动的流程,并提供主要模块的算法描述和示例代码。
主要模块的算法描述
-
商品信息模块
- 定义商品类,包括商品编号、商品名称、原价等属性。
- 从文件中读取商品信息,并将商品信息存储到一个列表中。
-
购物车模块
- 定义购物车类,包括添加商品、删除商品、计算总价等方法。
- 通过输入商品编号将商品添加到购物车中。
- 可以删除购物车中的商品。
- 计算购物车中商品的总价。
-
打折模块
- 定义打折类,包括根据消费金额打折、根据购买数量打折等方法。
- 根据消费金额打折:满足一定的消费金额可以获得一定的折扣。
- 根据购买数量打折:购买一定数量的商品可以获得一定的折扣。
-
主程序模块
- 循环显示商品列表,输入商品编号将商品添加到购物车中。
- 显示购物车中的商品信息及总价。
- 根据消费金额或购买数量计算折扣,计算打折后的总价。
- 输出最终的消费金额和节省金额。
示例代码
# 商品类
class Product:
def __init__(self, id, name, price):
self.id = id
self.name = name
self.price = price
# 读取商品信息
def read_products(filename):
products = []
with open(filename, 'r') as f:
for line in f:
data = line.strip().split(',')
product = Product(data[0], data[1], float(data[2]))
products.append(product)
return products
# 购物车类
class ShoppingCart:
def __init__(self):
self.items = []
# 添加商品到购物车
def add_item(self, product):
self.items.append(product)
# 删除购物车中的商品
def remove_item(self, product):
self.items.remove(product)
# 计算购物车中商品的总价
def calculate_total_price(self):
total_price = 0
for item in self.items:
total_price += item.price
return total_price
# 打折类
class Discount:
# 根据消费金额打折
@staticmethod
def calculate_discount_by_amount(total_price):
if total_price >= 500:
return 0.8
elif total_price >= 300:
return 0.9
else:
return 1.0
# 根据购买数量打折
@staticmethod
def calculate_discount_by_quantity(quantity):
if quantity >= 5:
return 0.9
elif quantity >= 3:
return 0.95
else:
return 1.0
# 主程序
def main():
products = read_products('products.txt')
shopping_cart = ShoppingCart()
while True:
print('商品列表:')
for product in products:
print('{} {} {}'.format(product.id, product.name, product.price))
choice = input('请输入商品编号(按q退出):')
if choice == 'q':
break
else:
product = next((p for p in products if p.id == choice), None)
if product is None:
print('输入有误,请重新输入!')
else:
shopping_cart.add_item(product)
print('购物车中的商品:')
for item in shopping_cart.items:
print('{} {} {}'.format(item.id, item.name, item.price))
total_price = shopping_cart.calculate_total_price()
print('总价:{}'.format(total_price))
discount_by_amount = Discount.calculate_discount_by_amount(total_price)
discount_by_quantity = Discount.calculate_discount_by_quantity(len(shopping_cart.items))
final_price = total_price * discount_by_amount * discount_by_quantity
saved_price = total_price * (1 - discount_by_amount) * (1 - discount_by_quantity)
print('应付金额:{}'.format(final_price))
print('节省金额:{}'.format(saved_price))
if __name__ == '__main__':
main()
注意:
- 以上代码示例仅供参考,实际应用中需要根据具体需求进行修改和完善。
- 代码中
products.txt文件需要自行创建,并包含商品信息(商品编号、商品名称、原价),每行一个商品信息,用逗号隔开。 - 该程序实现了简单的打折逻辑,可以根据实际需求添加更复杂的打折规则。
- 可以添加用户登录、商品库存等功能,使程序更完善。
- 可以将代码封装成函数或类,提高代码的可读性和可维护性。
原文地址: https://www.cveoy.top/t/topic/ovoX 著作权归作者所有。请勿转载和采集!