简体   繁体   中英

Python - Validation of an integer - except or except ValueError?

I've created the following test in Python 3.x:

answer = int(input("What's 5 x 8?"))
if answer == 40:
    print("Correct!")
else:
    print("Incorrect!")

answer = int(input("What's 4 + 7?"))
if answer == 11:
    print("Correct!")
else:
    print("Incorrect!")

answer = int(input("What's 9 - 4?"))
if answer == 5:
    print("Correct!")
else:
    print("Incorrect!")

but I don't know whether I should use except or except ValueError to validate each answer.

Using except :

while True:
    try:
        answer = int(input("What's 5 x 8?"))
        if answer == 40:
            print("Correct!")
        else:
            print("Incorrect!")
        break
    except:
        print("That's not a valid answer. Enter an integer.")
#This would be repeated for the two other questions

Using except ValueError :

while True:
    try:
        answer = int(input("What's 5 x 8?"))
        if answer == 40:
            print("Correct!")
        else:
            print("Incorrect!")
        break
    except ValueError:
        print("That's not a valid answer. Please enter an integer.")
#This would be repeated for the two other questions

I only want integers to be accepted (eg '400', '3', etc.). Which one is better to use in my case?

Bare except is pretty much never the right thing, so you probably want to be catching the ValueError .

The problem with bare except is that it'll catch anything including things like KeyboardInterrupt , SystemExit , etc. Even if you become a little more restrictive and do:

try:
    ...
except Exception:
    ...

You can still end up glossing over all sorts of programming errors (eg if you accidentally misspelled an attribute and the code was raising AttributeError -- You'd be catching that exception and tracking down the resulting bugs would be harder).

My rule is to only catch exceptions if you know how to handle them . In this case, you know how to handle a ValueError from that block of code, but you don't know how to handle TypeError , or AttributeError or pretty much anything else. So, you should handle the ValueError and nothing else.

如果要验证整数,则应使用ValueError。

Do not use bare except in the context you want to catch the exception. If you want to catch all kinds of exception not related to program exit , which is true for most of the cases, use except Exception . But it is always a good idea to be specific.

And in the while loop you are break ing out abruptly. If you want to break out only when the correct answer is recieved, then:

while True:
    try:
        x = int(input("8 + 21 :"))
    except ValueError:
        print("Enter a valid number")
    else:
        if x == 29:
            break
        else:
            continue  # this is not required, just being explicit

See if it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM