1

使用 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 的值,那么它应该打印出它不是一个数字,但它不是,有什么想法吗?

4

3 回答 3

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 and catch,因为输入可能不是数字。

于 2013-10-02T01:16:36.867 回答
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!")
于 2013-10-02T01:20:34.147 回答
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)
于 2013-10-02T06:15:09.557 回答