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

运费计算程序if/else语句异常及rate1未正常输出问题排查

问题分析与修复方案

问题1:if/else分支逻辑异常原因

你代码里把输入转成大写后,错误地和小写的"yes"做比较。international.upper()会将输入的"yes"转为"YES",此时条件== "yes"永远不成立,所以不管你输入"yes"还是"no",都会进入else分支,弹出continental的提问。

问题2:rate1无法正常输出原因

由于第一个if条件判断错误,国际运输场景被错误归入国内运输分支;同时若国内运输分支的条件也存在同样的大小写匹配问题,会进一步导致rate1无法被正确赋值。

修复后的代码

# This program calculates the shipping cost as shown in the slide
international = input("Are you shipping internationally (yes or no)? ")
rate1 = 5
rate2 = 10

# 修复:将比较目标改为大写"YES",匹配upper()转换后的结果
if international.upper() == "YES":
    shippingRate = rate2
else:
    continental = input("Are you shipping continental (yes or no)? ")
    # 同步修复此处的大小写匹配问题
    if continental.upper() == "YES":
        shippingRate = rate1
    else:
        shippingRate = rate2
        
print("The shipping rate is " + ("%.2f" % shippingRate)) 

额外优化提示

  • 也可以统一将输入转为小写后和"yes"比较,逻辑更直观:international.lower() == "yes"
  • 可添加输入合法性校验,避免用户输入非yes/no内容导致逻辑异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:15:23