You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写计算与应用折扣的Python函数技术需求

折扣计算函数实现

1. 单个价格折扣计算函数 calculate_discount

该函数接收原价与折扣百分比,返回折扣后的最终价格,同时加入基础参数校验确保输入合理性:

def calculate_discount(original_price, discount_percentage):
    # 校验输入合法性
    if original_price < 0:
        print("错误:原价不能为负数")
        return original_price
    if not (0 <= discount_percentage <= 100):
        print("错误:折扣百分比需在0-100之间")
        return original_price
    
    # 计算折扣后价格,保留两位小数
    discounted_price = original_price * (1 - discount_percentage / 100)
    return round(discounted_price, 2)

测试用例

# 常规20%折扣
print(calculate_discount(100, 20))  # 输出:80.0
# 无折扣
print(calculate_discount(50, 0))     # 输出:50.0
# 全额折扣
print(calculate_discount(200, 100))  # 输出:0.0
# 超出范围的折扣(返回原价)
print(calculate_discount(150, 120))  # 输出提示信息 + 150
# 负原价输入(返回原值)
print(calculate_discount(-30, 10))   # 输出提示信息 + -30

2. 批量价格折扣函数 apply_discount

接收价格列表与统一折扣百分比,对列表内每个价格调用calculate_discount处理,返回折扣后的新列表:

def apply_discount(price_list, discount_percentage):
    return [calculate_discount(price, discount_percentage) for price in price_list]

测试用例

# 正常批量折扣
print(apply_discount([100, 200, 50], 15))  # 输出:[85.0, 170.0, 42.5]
# 包含无效价格的批量处理
print(apply_discount([-10, 300, 75], 20))  # 输出提示信息 + [-10, 240.0, 60.0]

示例输入输出汇总

函数调用输出结果
calculate_discount(100, 20)80.0
calculate_discount(200, 100)0.0
apply_discount([100, 200, 50], 15)[85.0, 170.0, 42.5]
apply_discount([-10, 300, 75], 20)[-10, 240.0, 60.0](伴随错误提示)

内容的提问来源于stack exchange,提问作者Abhishek Tiramareddi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 20:51:04