模拟超市抹零结账的程序代码,模拟参加手机店打折活动代码,用python语言实现
时间: 2024-10-19 19:15:55 浏览: 35
为了演示这两个场景,我们将分别给出基本的Python代码示例。首先,我们先看一个简单的超市抹零结账的例子:
```python
class Product:
def __init__(self, name, price, min_price):
self.name = name
self.price = price
self.min_price = min_price
def checkout(products, cart):
total = 0
for item in cart:
price = item['product'].price * item['quantity']
if price < item['product'].min_price:
rounded_price = round(price, -int(math.floor(math.log10(price))) + 1) # 抹零处理
else:
rounded_price = price
total += rounded_price
return total
# 示例商品和购物车
products = [Product('苹果', 0.99, 0.5), Product('牛奶', 1.50, 1)]
cart = [{'product': products[0], 'quantity': 3}, {'product': products[1], 'quantity': 2}]
print(checkout(products, cart))
```
接下来,我们看一个简单的手机店打折活动的模拟代码:
```python
def discount_activity(product, discount_rate, condition):
original_price = product.price
if condition(original_price): # 判断是否满足折扣条件
discounted_price = original_price * (1 - discount_rate)
return discounted_price
else:
return original_price
# 示例产品和折扣条件
phone = {'name': 'iPhone', 'price': 8000}
discount_condition = lambda x: x >= 7000 # 当价格超过7000元时打9折
discounted_price = discount_activity(phone, 0.1, discount_condition)
print(f"{phone['name']} 打完折后价格:{discounted_price}")
```
请注意,这只是一个简化的版本,实际应用中可能需要更复杂的输入验证和错误处理。同时,这些代码可以根据需求进一步优化和扩展。
阅读全文