Python摄氏度与华氏度转换代码if为真仍执行else分支问题求解
温度转换代码问题排查与修复
问题根因
你代码的核心错误是判断逻辑用错了变量:
- 你将用户输入的温度数值存在了
temperature变量,温度单位存在了type变量,但if判断时却拿数值类型的temperature和字符串celsius/fahrenheit比较,二者类型和内容完全不匹配,所以所有判断都会直接进入else分支。 - 额外问题:
type是Python内置关键字,直接用作变量名会覆盖其原有功能,属于不规范写法;同时原代码未处理大小写输入,用户输入大写的Celsius/Fahrenheit时也会匹配失败。
修复后代码
temperature = int(input('what is the temperature? ')) temp_unit = input('is it in celsius or fahrenheit: ').lower() if temp_unit == 'celsius': converted_temp = (temperature * 9 / 5) + 32 print("The converted temp in fahrenheit is: ", converted_temp) elif temp_unit == 'fahrenheit': converted_temp = (temperature - 32) * 5 / 9 print('The converted temperature in celsius is:', converted_temp) else: print("SORRY! Enter either Celsius or Fahrenheit")
改动说明
- 把存储温度单位的变量名从
type改为temp_unit,避免和Python内置的type()函数冲突 - 调整判断逻辑,改为校验存储单位的
temp_unit变量,判断前统一转为小写,兼容大小写输入场景 - 修正了原代码中打印语句的拼写错误
内容的提问来源于stack exchange,提问作者Juggle
相关产品推荐
相关产品推荐

