【问题标题】:Specific Try and Except具体尝试和除外
【发布时间】:2014-10-29 20:10:18
【问题描述】:
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."

【问题讨论】:

    标签: python input try-catch except


    【解决方案1】:

    将对input 的调用移到try: 块之外,并仅将对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
    

    【讨论】:

    • 我很惊讶这是最好的方法,至于像KeyError 这样的东西,你可以用e.args 得到它的原因,但这只是返回消息。奇怪。
    • 您可以从e.args 中包含的消息中获取输入值,但这比我的解决方案更复杂。我故意保持代码简单,以免超出 OP 的经验水平。
    • 我可能会这样做,否则会太啰嗦。不过,我很惊讶传递给BaseException 的参数不能以相同的方式访问。
    【解决方案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
    

    【讨论】:

    • 在您的情况下,空输入将允许循环退出。
    猜你喜欢
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    • 2020-12-17
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多