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

Python快递运费计算程序出现无限循环重复输出问题求助

问题根因

你代码的无限循环问题出在末尾的while(more == "n")逻辑块:
当用户输入n后,more变量的值会一直保持为n,这个循环内部没有任何修改more变量的代码,也没有退出循环的逻辑,所以会一直重复执行打印总运费的语句,直接去掉这层while循环、直接打印结果即可解决问题。

其他需修正的代码问题

  • 重量区间1-2磅的逻辑里,你把赋值等于号写错成了冒号:op1:(lbs * 1.10),运行会触发变量未定义报错
  • 多个连续if判断可以替换为elif,避免不必要的分支校验
  • 不建议使用eval处理用户输入,直接用float()转换更安全,避免用户输入恶意代码被执行
  • 输入校验缺失:没有处理用户输入非y/n的场景,也没有处理重量为负数的场景

修正后可正常运行的代码

more = "y"
count = 0
total = 0

while more == "y":
    # 处理用户输入的重量
    try:
        lbs = float(input("请输入包裹重量(单位:磅):"))
    except ValueError:
        print("请输入合法的数字重量")
        continue
    
    if lbs <= 0:
        print("你的包裹无法配送")
    elif lbs <= 2:
        cost = lbs * 1.10
        count += 1
        total += cost
        print(f"当前包裹运费为:{cost}")
    elif lbs <= 6:
        cost = lbs * 2.20
        count += 1
        total += cost
        print(f"当前包裹运费为:{cost}")
    elif lbs <= 10:
        cost = lbs * 3.70
        count += 1
        total += cost
        print(f"当前包裹运费为:{cost}")
    else:
        cost = lbs * 3.80
        count += 1
        total += cost
        print(f"当前包裹运费为:{cost}")
    
    # 询问是否继续输入
    while True:
        more = input("你需要录入另一个包裹吗?<y/n>:").strip().lower()
        if more in ("y", "n"):
            break
        print("请输入合法的选项y或n")

print(f"你的总运费为:{total},共{count}个包裹")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:39:00