Python check for integer input

You’re using eval, which evaluate the string passed as a Python expression in the current context. What you want to do is just

data = raw_input('Enter a number: ')
try:
    number = int(data)
except ValueError:
    print "I am afraid %s is not a number" % data
else:
    if number > 0:
        print "%s is a good number" % number
    else:
        print "Please enter a positive integer"

This will try to parse the input as an integer, and if it fails, displays the error message.

Leave a Comment