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

重量转换程序异常:为何仅执行else分支而非if分支?

重量转换代码未执行if分支的原因

你的代码和运行情况如下:

原代码

weight = float(input("weight: "))
unit = input("(K)g or (L)bs: ")

if unit.upper == "K":
    converted = weight*2.2
    print("Weight in Lbs: " + str(converted))
else:
    converted = weight/2.2
    print("Weight in kgs: " + str(converted))
print("Conversion done")

运行结果

weight: 15

(K)g or (L)bs: k

Weight in kgs: 6.8181818181818175

Conversion done


错误原因

问题出在if unit.upper == "K"这一行:upper是字符串的方法,必须加括号()才能调用执行,返回转换后的大写字符串。你现在写的unit.upper是直接引用这个方法对象,而不是调用它得到结果。拿方法对象和字符串"K"做比较,结果永远是False,所以程序会一直进入else分支。

修正后的代码

weight = float(input("weight: "))
unit = input("(K)g or (L)bs: ")

if unit.upper() == "K":
    converted = weight*2.2
    print("Weight in Lbs: " + str(converted))
else:
    converted = weight/2.2
    print("Weight in kgs: " + str(converted))
print("Conversion done")

修改后输入k时,unit.upper()会返回"K",条件成立后就能正确执行if分支的转换逻辑了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 04:40:33