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

Python计算不同重量包裹总运费程序出现总价计算错误问题

问题原因

代码的区间判断逻辑存在错误,将区间判断需要的and逻辑运算符错写为or:

  • 你写的elif (weight > 2 or weight <= 6)逻辑是只要重量大于2 或者 重量小于等于6就触发,所有大于2的重量都会满足这个条件,直接使用28的费率计算,后续的25、23费率分支永远不会被触发,因此总运费高于预期。
  • 正确的区间判断应该用and,表示重量同时满足两个边界条件才匹配对应费率。

另外还有一个小优化点:包裹数量为正整数,使用int()接收输入比float()更合理,避免出现输入小数的异常情况。

修正后代码

max_2 = 30 
between_2_6 = 28 
between_6_12 = 25 
over_12 = 23 
i = 0  # 循环计数变量
total_price = 0  # 总运费初始值

# 包裹数量为整数,用int类型接收输入
parcel = int(input("How many parcels do you want to send?  "))

while i < parcel:
    i += 1
    weight = float(input("How much does your parcel weigh " + str(i) + "?: "))
    if weight <= 2:                                     
        price = weight * max_2 
    # 将or替换为and,实现区间匹配逻辑
    elif weight > 2 and weight <= 6: 
        price = weight * between_2_6 
    elif weight > 6 and weight <= 12: 
        price = weight * between_6_12 
    elif weight > 12: 
        price = weight * over_12                                                  
   
    total_price += price
 
print(str(total_price) + "USD")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 05:12:02