2014-10-29 41 views
0
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."具体的尝试和例外

回答

3

将呼叫转移到try:区块以外的input,并且只将呼叫置于int之内。这将确保userInput定义,让你然后用if语句检查其值:

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 
+0

我很惊讶,这是最好的办法这样做,至于类似'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

+0

您可以从'e.args'中包含的消息中获取输入值,但这比我的解决方案更为复杂。我有目的地保持代码简单,以便不超过OP的经验水平。 – iCodez 2014-10-29 20:22:52

+0

我可能会这样做,无论如何,它会太冗长。不过,我很惊讶传递给'BaseException'的参数不能以相同的方式访问。 – 2014-10-29 20:24:07

2

也许是这样的:

keepgoing = True 
while keepgoing: 
    try: 
     userInput = input("Please enter an integer: ") 
     if userInput == "": 
      print("Empty value") 
      raise ValueError 
     else: 
      userInput = int(userInput) 
    except ValueError: 
     print("Sorry, wrong value.") 
    else: 
     keepgoing = False 
+0

在你的情况下,空输入将允许循环退出。 – njzk2 2014-10-29 20:23:19

+0

我修好了..... – jgritty 2014-10-29 20:50:16

+0

@jgritty。错过了......谢谢! – micebrain 2014-11-04 07:31:33