用if else和Switch语句输出关于商品折扣计算
时间: 2024-10-29 11:12:38 浏览: 26
如果你需要通过 `if-else` 和 `switch` 语句来计算商品折扣,通常会根据不同的折扣条件来设定。这里是一个简单的例子:
```python
# 定义商品原价和折扣规则
price = 100
discount_conditions = {
"new_product": 0.95, # 新品折扣
"seasonal_sale": 0.85, # 季节性促销
"bulk_purchase": 0.9, # 批量购买折扣
"none": 1 # 没有折扣
}
# 使用 if-else 来计算折扣
if "new_product" in discount_conditions:
discount_amount = price * discount_conditions["new_product"]
elif "seasonal_sale" in discount_conditions:
discount_amount = price * discount_conditions["seasonal_sale"]
elif "bulk_purchase" in discount_conditions:
discount_amount = price * discount_conditions["bulk_purchase"]
else:
discount_amount = price
# 或者使用 switch 语句(某些编程语言如Java、C#支持)
discount_amount = price
switch (discount_condition_key): # 假设discount_condition_key存在上述字典中
case "new_product":
discount_amount *= discount_conditions["new_product"]
case "seasonal_sale":
discount_amount *= discount_conditions["seasonal_sale"]
case "bulk_purchase":
discount_amount *= discount_conditions["bulk_purchase"]
default:
discount_amount = price
# 输出折扣后的价格
final_price = price - discount_amount
print(f"折扣后的价格为: {final_price}")
阅读全文