Python语句的Python Temperature Converter问题

时间:2014-07-08 04:49:57

标签: python

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)

以上是我到目前为止在温度转换器上的代码,但我的问题是它似乎是在忽略'基本上所有代码除了接受base_temperature然后将其从摄氏度转换为fahrenheit和kelvin。即使当我为base_unit输入华氏度或开尔文时,它似乎忽略了这一点,只是通过"如果base_unit等于摄氏度"代码无论输入到base_unit。因此,例如,如果我为base_temperature和" fahrenheit"说出100。对于base_unit,它会吐出来#摄氏度为100,华氏度为212,开尔文为373.15。我对Python非常陌生,所以我不完全确定如何对此进行故障排除,我是否需要创建一个实际的函数来分别从摄氏温度,华氏温度或开尔温度转换?

3 个答案:

答案 0 :(得分:5)

你的问题是那个

base_unit.lower() == "celsius" or "c"

解析为

(base_unit.lower() == "celsius") or ("c")

"c"可隐式转换为布尔值(它是True),因此条件始终为true。要解决此问题,请尝试以下方法:

base_unit.lower() == "celsius" or base_unit.lower() == "c":

答案 1 :(得分:1)

为了修复此行并将其转换为更加pythonic的风格:

base_unit.lower() == "celsius" or "c"

将其更改为:

if base_unit.lower() in ["celsius", "c"]:

答案 2 :(得分:-1)

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))