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

Python while循环中or运算符使用错误导致温度转换程序异常

Python while循环中or运算符使用错误导致温度转换程序异常

兄弟我太懂你这种越调越懵的感觉了!咱们直接揪出问题的根源——你写的while循环条件逻辑错啦!

你现在的循环条件是while unit != ("F" or "C"),但Python里这个表达式的运算逻辑和你想的完全不一样:它会先计算"F" or "C",因为"F"是非空字符串(在Python里非空字符串会被视为布尔值True),所以"F" or "C"的结果直接就是"F"。这就导致你的循环条件等价于while unit != "F",那你输入C的时候,这个条件是成立的,循环就会一直跑,反复让你输入单位,这就是为啥程序不认C的原因!

咱们把这个条件改成两种正确写法之一就行:

  1. 用not in来判断是否不在合法选项里,可读性最高:
while unit not in ("F", "C"):
  1. 用and把两个不等于的条件连起来,明确表达“既不是F也不是C”:
while unit != "F" and unit != "C":

另外顺带提一嘴,你代码里的变量名有点小问题,比如把转换后的华氏/摄氏温度都存在c_temp里,其实可以改成f_temp和c_temp,这样自己看着也更清楚。

最后给你贴修正后的完整代码:

# converts between C and F

# conversion = C * 9/5 +32 = F
unit = input("is the temperature in Celsius or Fahrenheit (C/F): ")
temp = float(input("Enter the temperature: "))

while unit not in ("F", "C"):
    unit = input("Please enter the unit of temperature, Celsius or Fahrenheit (C/F): ")

if unit == "C":
    f_temp = (temp * 9/5) + 32
    print(f_temp)
elif unit == "F":
    c_temp = (temp - 32) / (9/5)
    print(c_temp)

刚开始写Python踩这种逻辑运算符的坑太正常了,别慌,多试几次就摸透啦!

备注:内容来源于stack exchange,提问作者Ihsan Ali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 14:59:28