(Python)如果用户输入不正确,如何结束代码的基本方法?



这是我第一次尝试写代码。我看了python的基础知识,决定从简单的开始。我做了一个华氏和摄氏度的计算器反之亦然。正如您在下面的代码中看到的那样,我希望在两次要求用户输入错误的变量时,程序停止运行。如果用户不显示A或B,我使用if、elif和else语句,但是,我尝试处理所询问的整数的任何操作总是以ValueError结束代码。基本上,如果用户输入一个字母而不是一个数字,我希望代码显示"请再试一次!">

```
# printing all conversion options
print("Conversion Options")
print("A. Celcius to Fahrenheit")
print("B. Fahrenheit to Celcius")
# Selecting the options
option = input("Select Option A or B: ")
# Value of Degree in conversion
value = float(input("Enter Degree Amount: "))
# Conversion and option
if option == 'A':
new_value = (value * 1.8) + 32
elif option == 'B':
new_value = (value - 32) * 5/9
else:
print("You did not select A or B. Try again!")
exit()
# Enjoy your results
print("Conversion is now complete!")
print(new_value,"degrees")
```

基本上,如果用户输入一个字母而不是一个数字,我希望代码显示"please try again ">

最好的方法是将其隔离在函数中:

def ask_user(prompt, verify, convert, reprompt="please try again!", limit=5):
value = input(prompt)
if verify(value):
return convert(value)
for i in range(limit):
print(reprompt)
value = input(prompt)
if verify(value):
return convert(value)
raise RuntimeError('Exceeded input attempt limit')

需要输入验证。我已经用try except的方法来做这件事,但是你也可以先捕获输入,然后检查它是否是一个数字,而不是依赖于异常。我还为option添加了验证,这样如果选项从一开始就错误,用户就不必输入数字了。

# printing all conversion options
print("Conversion Options")
print("A. Celcius to Fahrenheit")
print("B. Fahrenheit to Celcius")
# Selecting the options
option = input("Select Option A or B: ")
if option not in ['A', 'B']:
print('Not a valid option. Try again')
exit(1)
# Value of Degree in conversion
try:
value = float(input("Enter Degree Amount: "))
except ValueError as e:
print('Not a valid number. Try again')
exit(1)
# Conversion and option
if option == 'A':
new_value = (value * 1.8) + 32
elif option == 'B':
new_value = (value - 32) * 5/9
else:
print("You did not select A or B. Try again!")
exit()
# Enjoy your results
print("Conversion is now complete!")
print(new_value, "degrees")

评论中的一些问题:

ValueError as e:将异常赋值给变量e。然后,我们可以处理异常并做一些日志记录或对异常做其他事情:

# Value of Degree in conversion
try:
value = float(input("Enter Degree Amount: "))
except ValueError as e:
print('Exception message: ')
print(e)
print('Not a valid number. Try again')
exit(1)

输出:

Enter Degree Amount: t
Exception message: 
could not convert string to float: 't'
Not a valid number. Try again

最新更新