使用Try / Except的正确方法是什么?
我是Python的新手,只是想学习这种新技术,所以任何想法为什么这不起作用?
temp=input("Please choose an option: ")
try:
if temp == ("1"):
fc=input("Fahrenheit: ")
fer(int(fc))
if temp == ("2"):
cf=input("Celsius: ")
cel(int(cf))
except ValueError:
print("It looks like you input a value that wasn't a number!")
如果你把“temp”中的值设置为不是1或2而不是它应该打印出来的那么它不是数字但是没有,那么有什么想法吗?
答案 0 :(得分:3)
“看起来您输入的值不是数字!”将在您的try块中出现异常时打印。你想做的是:
temp=input("Please choose an option: ")
try:
if temp == ("1"):
fc=input("Fahrenheit: ")
fer(int(fc))
elif temp == ("2"):
cf=input("Celsius: ")
cel(int(cf))
else:
print("It looks like you input a value that wasn't 1 or 2!")
except ValueError:
print("It looks like you input a value that wasn't a number!")
你必须保持try和catch,因为输入可能不是数字。
答案 1 :(得分:2)
temp=input("Please choose an option: ")
try:
if temp == ("1"): # is temp == "1"
fc=input("Fahrenheit: ") # if yes, get number
fer(int(fc)) # convert to int, this can raise an exception
if temp == ("2"): # is temp == "2"
cf=input("Celsius: ") # if yes, get number
cel(int(cf)) # this can raise an exception
except ValueError: # capture all ValueError exceptions
print("It looks like you input a value that wasn't a number!")
temp
的值永远不会在您的代码中引发异常(只有输入的解析可以),所以它只是通过。您需要手动添加检查以确保temp
是有效条目之一。
更好的方法是(并且您可以通过例外验证temp
):
def handle_f():
fc=input("Fahrenheit: ") # if yes, get number
fer(int(fc)) # convert to int, this can raise an exception
def handle_C():
cf=input("Celsius: ") # if yes, get number
cel(int(cf)) # this can raise an exception
fun_dict = {"1": handle_f, "2": handle_c}
try:
fun_dict[temp]()
except KeyError: # handle temp not being valid
print('not a valid temperature type')
except ValueError:
print("It looks like you input a value that wasn't a number!")
答案 2 :(得分:0)
我认为从用户那里抽象读取int的过程更简洁:
def input_int(prompt):
try:
return int(input(prompt))
except ValueError:
print("It looks like you input a value that wasn't a number!")
temp=input("Please choose an option: ")
if temp == ("1"):
fc=input_int("Fahrenheit: ")
fer(fc)
if temp == ("2"):
cf=input_int("Celsius: ")
cel(cf)