温度转换器问题

时间:2015-03-11 04:38:31

标签: python

我正在尝试使用python制作温度转换器。目标是让用户输入当前温度,将其转换为浮动,然后转换它。我几乎完成了这一部分。但是,为了使代码不那么脆弱,我试图找出一种方法来阻止用户将非数值作为初始温度。你能帮我搞清楚吗?此外,我们非常感谢任何其他错误检查建议。

#We will begin with asking the user for what the temperature they want to use and converts it to a float
temperature =float(input("Please enter the whole number value of the temperature. "))

#Next we will ask the user if they are using Fahrenheit and Celcius
unit = input("Is this celcius or fahrenheit? ")

#Checks to see if the unit used is  Celcius
if unit == "celcius"  or unit == "Celcius":
    celcius = temperature * 9/5 + 32.0
    print(celcius)
elif unit == "fahrenheit" or unit == "Fahrenheit":
    fahrenheit = (temperature - 32.0) * 5/9
    print(fahrenheit)
else:
    print("Invalid unit. Exiting program.")

2 个答案:

答案 0 :(得分:0)

怎么样

while True:
    try:
        temperature = float(input("Please enter the whole number value of the temperature. "))
        break
    except ValueError:
        print('Invalid input')

此外,

if unit.lower() == "celcius":

通常比

更安全
if unit == "celcius"  or unit == "Celcius":

答案 1 :(得分:0)

#We will begin with asking the user for what the temperature they want to use and converts it to a float
while True:
userInput = input("Please enter the whole number value of the temperature. ")
try:
    temperature = float(userInput)
    break
except ValueError:
    print("Not a number")

#Next we will ask the user if they are using Fahrenheit and Celcius
unit = input("Is this celcius or fahrenheit? ")

#Checks to see if the unit used is  Celcius
if unit == "celcius"  or unit == "Celcius":
    celcius = temperature * 9/5 + 32.0
    print(celcius)
elif unit == "fahrenheit" or unit == "Fahrenheit":
    fahrenheit = (temperature - 32.0) * 5/9
    print(fahrenheit)
else:
    print("Invalid unit. Exiting program.")