Python 温度转换器中的 if 语句问题
base_temperature = raw_input("Temperature to convert: ")
temp = int(base_temperature)
base_unit = raw_input("Current unit of measure (Please choose Celsius, Fahrenheit, or Kelvin): ")
base_unit = base_unit.lower()
if base_unit.lower() == "celsius" or "c":
celsius = temp
fahrenheit = celsius * 9/5 + 32
kelvin = celsius + 273.15
print "%s in Celsius is %s in Fahrenheit and %s in Kelvin." % (celsius, fahrenheit, kelvin)
elif base_unit.lower() == "kelvin" or "k":
kelvin = temp
fahrenheit = kelvin * 9/5 - 459.67
celsius = kelvin - 273.15
print "%s in Kelvin is %s in Fahrenheit and %s in Celsius." % (kelvin, fahrenheit, celsius)
elif base_unit.lower() == "fahrenheit" or "f":
fahrenheit = temp
celsius = (fahrenheit - 32) * 5/9
kelvin = (fahrenheit + 459.67) * 5/9
print "%s in Fahrenheit is %s in Celsius and %s in Kelvin." % (fahrenheit, celsius, kelvin)
上面是我目前写的温度转换器的代码,但我遇到的问题是,它似乎“忽略”了几乎所有的代码,只是接收了基本温度,然后把它从摄氏度转换成华氏度和开尔文。即使我把基本单位设置为华氏度或开尔文,它似乎也不管这些,还是只执行“如果基本单位是摄氏度”的那部分代码。举个例子,如果我输入100作为基本温度,输入“fahrenheit”作为基本单位,它就会返回“100摄氏度是212华氏度和373.15开尔文”。我对Python非常陌生,所以不太确定该怎么解决这个问题,是不是需要为摄氏度、华氏度和开尔文分别创建一个实际的转换函数呢?
3 个回答
-1
在编程中,有时候我们会遇到一些问题,特别是在使用某些工具或库的时候。这些问题可能会让我们感到困惑,尤其是当我们刚开始学习编程的时候。比如,有人可能会在使用某个特定的功能时,发现它并没有按照预期工作。这个时候,查看其他人的经验和解决方案就显得特别重要。
在StackOverflow上,很多人会分享他们遇到的问题和解决办法。通过这些讨论,我们可以学习到如何处理类似的情况,避免走弯路。无论是代码错误、功能不正常,还是其他技术问题,大家都会在这里互相帮助,分享知识。
所以,如果你在编程的过程中遇到困难,不妨去看看这些讨论,可能会找到你需要的答案或者灵感。
x = float(input("the weather today is (temperature in Celsius) : "))
f = 9 * x / 5 + 32
print("%.1f C is %.1f F " % (x, f))
f = float(input("the weather today is (temperature in Fahrenheit ) :"))
x = (f - 32) * 5 / 9
print("%.1f F is %.1f C ." % (f, x))
1
为了修正这一行代码,并让它更符合Python的风格:
base_unit.lower() == "celsius" or "c"
可以改成:
if base_unit.lower() in ["celsius", "c"]:
5
你的问题是
base_unit.lower() == "celsius" or "c"
解析成
(base_unit.lower() == "celsius") or ("c")
"c"
会被自动转换成布尔值(也就是 True
),所以这个条件总是成立。要解决这个问题,可以试试下面这个:
base_unit.lower() == "celsius" or base_unit.lower() == "c":