Python温度转换器中请求的错误处理帮助



我是一名编程专业的学生,从事Python作业,设计一个可以将摄氏度转换为华氏度或其他方式的应用程序。我当前的代码在获得预期值时正在工作,但在输入不符合预期格式时遇到了一些问题:

temp = "" #set initial value for temp variable
celsfahr = "" #set initial value for Celsius or Fahrenheit

while temp != "exit":
temp, celsfahr = input("Enter a temperature in Celsius or Fahrenheit (examples: 32 Celsius, 500 Fahrenheit, -10 Celsius:) ").split()
if temp.isnumeric():
temp = int(temp)
if celsfahr == "Fahrenheit":
print(temp, "Fahrenheit equals", ((temp-32)*.556), "Celsius.")
else:
if celsfahr == "Celsius":
print(temp, "Celsius equals", ((temp*1.8)+32), "Fahrenheit.")
else:
if temp.lower() == "exit":
temp = temp.lower()
print("Goodbye.")
else:
print("I don't understand. Try again.n")

我试图解决的几个问题:

  1. 如何在输入/拆分中添加一个检查,以便在输入两个空格以外的值时程序不会崩溃
  2. 相关,如何接受";退出";作为输入字段中的值,并进行拆分
  3. 如何触发";我不明白"之前的错误消息——现在除了摄氏度或华氏度之外的意外值会将程序返回到输入,但不会显示错误

你过早分手,这会让你感到悲伤。请使用以下方法。您将检查您的输入在拆分时是否包含2个值,分别用于转换或1或退出消息。

userInput = ""
while userInput != "exit":
userInput = input("Enter a temperature in Celsius or Fahrenheit (examples: 32 Celsius, 500 Fahrenheit, -10 Celsius:) ")
data = userInput.split();
if len(data)==2:
temp = data[0]
unit = data[1]
if temp.isnumeric():
temp = int(temp)
if unit.title() == "Fahrenheit":
print(temp, "Fahrenheit equals", ((temp-32)*5/9), "Celsius.")
elif unit.title() == "Celsius":
print(temp, "Celsius equals", ((temp*9/5)+32), "Fahrenheit.")
elif len(data)==1:
userInput = data[0].lower()
if userInput == "exit":
print("Goodbye.")
else:
print("I don't understand. Try again.n")

我还为你安排了几件事。我用的是实际的分数(5/9(,而不是你在里面的数字。这样更准确。我还将单位变量重命名为unit

最新更新