具体尝试和除外

时间:2014-10-29 20:10:18

标签: python input try-catch except

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."

2 个答案:

答案 0 :(得分:3)

将呼叫移至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

答案 1 :(得分: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