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

如何定义接收重量参数并输出运费的Python函数,适配if elif分支逻辑

运费计算函数封装实现

你可以将不同运输方式的运费计算逻辑分别封装为独立函数,直接传入重量参数即可返回对应运费,完整可运行代码如下:

# 普通陆运运费计算函数:传入重量(单位:磅)返回运费
def calc_ground_shipping(weight):
    if weight <= 2:
        return weight * 1.50 + 20
    elif weight <= 6:
        return weight * 3.00 + 20
    elif weight <= 10:
        return weight * 4.00 + 20
    else:
        return weight * 4.75 + 20

# 陆运 premium 为固定定价,直接定义常量即可,也可根据需求封装为无参函数
COST_GROUND_PREMIUM = 125.00

# 无人机运费计算函数:传入重量(单位:磅)返回运费
def calc_drone_shipping(weight):
    if weight <= 2:
        return weight * 4.50
    elif weight <= 6:
        return weight * 9.00
    elif weight <= 10:
        return weight * 12.00
    else:
        return weight * 14.25

# 调用示例
if __name__ == "__main__":
    weight = float(input("请输入包裹重量:"))
    cost_ground = calc_ground_shipping(weight)
    print(f"普通陆运运费:${round(cost_ground, 2)}")
    print(f"Premium陆运运费:${round(COST_GROUND_PREMIUM, 2)}")

    drone_weight = float(input("请输入无人机运输的包裹重量:"))
    cost_drone = calc_drone_shipping(drone_weight)
    print(f"无人机运费:${round(cost_drone, 2)}")

逻辑说明

  • 所有if elif判断规则完全复用你原有计算逻辑,仅将全局变量计算改为函数内返回值,计算结果和原代码完全一致
  • 封装后可在任意位置直接调用函数传重量参数获取结果,无需重复编写判断逻辑,比如要计算3磅包裹的陆运运费,直接写calc_ground_shipping(3)即可拿到对应结果
  • 如果需要统一调用入口,可额外新增一个多运输方式适配函数:
def calc_shipping_cost(weight, shipping_type="ground"):
    if shipping_type == "ground":
        return calc_ground_shipping(weight)
    elif shipping_type == "ground_premium":
        return COST_GROUND_PREMIUM
    elif shipping_type == "drone":
        return calc_drone_shipping(weight)
    else:
        raise ValueError("仅支持的运输类型:ground/ground_premium/drone")

内容的提问来源于stack exchange,提问作者Chris D

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:45:05