I am trying to allow a user to input into my program, however when they enter a string my program fails. It is for a bigger program but was trying to correct the problem, I have so far:
data = raw_input('Enter a number: ')
number = eval(data)
if type(number) != int:
print"I am afraid",number,"is not a number"
elif type(number) == int:
if data > 0:
print "The",number,"is a good number"
else:
print "Please enter a positive integer"
when the user enters a string, it returns:
number = eval(data)
File "<string>", line 1, in <module>
NameError: name 'hel' is not defined
Any help would be most appreciated.
You can just use
int(raw_input())
to convert the input to an int.Never evaluate untrusted user input using eval, this will allow a malicious user to take over your program!
You're using
eval
, which evaluate the string passed as a Python expression in the current context. What you want to do is justThis will try to parse the input as an integer, and if it fails, displays the error message.
Why is no one mentioning regular expressions ? The following works for me, adjust the regex to fit your needs.
Tests: