Python温度应用单数字输入判断异常:9被识别为大于27问题排查
问题产生原因
异常核心是执行了字符串而非数值类型的比较:
- Python中
input()函数默认返回字符串类型,你没有将输入转成整数,直接和str(27)、str(32)做比较 - 字符串的大小比较规则是逐位对比字符的Unicode编码值:比如输入个位数
"9"时,首先对比第一位字符'9'和'3'(来自"32"的第一位),'9'的编码值远大于'3',因此会判定"9" > "32"为真,触发温度过高的错误逻辑;而双位数输入时首位字符对比逻辑刚好和数值大小逻辑一致,所以看起来运行正常 - 代码开头定义的
temperature = range(-30,55)完全没有作用,会被后续的input赋值直接覆盖,属于无效代码
修复方案
按照以下步骤修改即可:
- 拿到输入后直接转换为整数类型,所有大小判断都用数值执行,不要转字符串比较
- 合并重复的判断分支,优化逻辑结构避免冗余代码
修复后完整代码如下:
# 直接将输入转换为整数 temperature = int(input("What is the temperature in Celcius? ")) print("Temperature: " + str(temperature) + " degrees Celcius") if temperature < 27: print("Plant is too cold") sum = 27 - temperature print("Recommended temperature increase:" + str(sum) + " degrees Celcius") print("Remember to keep your plant between 27 and 32 degrees!") elif temperature > 32: print("Plant is too warm") sum = temperature - 32 print("Recommended temperature decrease:" + str(sum) + " degrees Celcius") print("Remember to keep your plant between 27 and 32 degrees!") else: print("Plant temperature is nominal")
内容的提问来源于stack exchange,提问作者JMWrites
相关产品推荐
相关产品推荐

