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