continue = True
while continue:
try:
userInput = int(input("Please enter an integer: "))
except ValueError:
print("Sorry, wrong value.")
else:
continue = False
对于上面的代码,我将如何能够赶上一个特定的ValueError
?我的意思是,如果用户输入一个非整数,我会打印出"Sorry, that is not an integer."
。但是如果用户输入是空的输入,我会打印出"Empty Input."
。具体的尝试和例外
我很惊讶,这是最好的办法这样做,至于类似'KeyError'的东西,你可以通过['e.args']得到它的原因(http://stackoverflow.com/questions/23139024/how-do-i-find-out-what- key-failed-in-python-keyerror/23139085#23139085),但这只是返回此消息。奇怪。 – 2014-10-29 20:17:21
您可以从'e.args'中包含的消息中获取输入值,但这比我的解决方案更为复杂。我有目的地保持代码简单,以便不超过OP的经验水平。 – iCodez 2014-10-29 20:22:52
我可能会这样做,无论如何,它会太冗长。不过,我很惊讶传递给'BaseException'的参数不能以相同的方式访问。 – 2014-10-29 20:24:07