Python 特定尝试和例外

Python 特定尝试和例外,python,input,try-catch,except,Python,Input,Try Catch,Except,对于上面的代码,如何捕获特定的ValueError?我的意思是,如果用户输入一个非整数,我会打印出“对不起,那不是整数。”。但是如果用户输入是空输入,我会打印出“空输入”。 将调用移动到输入块之外的尝试:块,并仅将调用int放在块内部。这将确保定义了userInput,允许您使用if语句检查其值: continue = True while continue: try: userInput = int(input("Please enter an integer: "

对于上面的代码,如何捕获特定的
ValueError
?我的意思是,如果用户输入一个非整数,我会打印出“对不起,那不是整数。”。但是如果用户输入是空输入,我会打印出
“空输入”。

将调用移动到
输入
块之外的
尝试:
块,并仅将调用
int
放在块内部。这将确保定义了
userInput
,允许您使用if语句检查其值:

continue = True
while continue:
     try: 
        userInput = int(input("Please enter an integer: "))
     except ValueError:
        print("Sorry, wrong value.")
     else:
        continue = False

将调用移动到
input
块之外的
try:
块,并仅将调用
int
放在块内。这将确保定义了
userInput
,允许您使用if语句检查其值:

continue = True
while continue:
     try: 
        userInput = int(input("Please enter an integer: "))
     except ValueError:
        print("Sorry, wrong value.")
     else:
        continue = False

也许是这样的:

keepgoing = True
while keepgoing:
    userInput = input("Please enter an integer: ")  # Get the input.
    try:
        userInput = int(userInput)  # Try to convert it into an integer.
    except ValueError:
        if userInput:  # See if input is non-empty.
            print("Sorry, that is not an integer.")
        else: # If we get here, there was no input.
            print("Empty input")
    else:
        keepgoing = False

也许是这样的:

keepgoing = True
while keepgoing:
    userInput = input("Please enter an integer: ")  # Get the input.
    try:
        userInput = int(userInput)  # Try to convert it into an integer.
    except ValueError:
        if userInput:  # See if input is non-empty.
            print("Sorry, that is not an integer.")
        else: # If we get here, there was no input.
            print("Empty input")
    else:
        keepgoing = False

我很惊讶这是最好的方法,对于像
KeyError
这样的东西,你可以得到导致它的原因,但这只是返回了消息。奇怪。您可以从
e.args
中包含的消息中获取输入值,但这比我的解决方案更复杂。我故意让代码简单,以免超过OP的经验水平。我可能会这样做,否则会太冗长。尽管如此,我还是很惊讶传递给
BaseException
的参数不能以相同的方式访问。我很惊讶这是最好的方法,对于类似
KeyError
的东西,您可以得到导致它的原因,但这只返回了相应的消息。奇怪。您可以从
e.args
中包含的消息中获取输入值,但这比我的解决方案更复杂。我故意让代码简单,以免超过OP的经验水平。我可能会这样做,否则会太冗长。不过,我还是很惊讶传递给
BaseException
的参数不能以相同的方式访问。在您的情况下,空输入将允许循环退出。在您的情况下,空输入将允许循环退出。