2

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.

5
  • possible duplicate of Python misidentification of int values Commented Feb 25, 2014 at 20:45
  • 8
    eval(raw_input(...)) is a very bad idea
    – lanzz
    Commented Feb 25, 2014 at 20:47
  • 1
    does str.isdigit exist in Python2?
    – Adam Smith
    Commented Feb 25, 2014 at 20:47
  • @lanzz Yes, it creates a potential security risk: what should be done instead? Commented Feb 25, 2014 at 20:47
  • @adsmith, yes, and it discriminates between floats and ints, clever
    – wnnmaw
    Commented Feb 25, 2014 at 20:52

3 Answers 3

8

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.

8
  • You could do this more directly by using print "{:d} is a good number".format(data) inside the try branch
    – wnnmaw
    Commented Feb 25, 2014 at 20:49
  • @wnnmaw OP wants to check if the number is positive after, so it's better for him to store it in a variable Commented Feb 25, 2014 at 20:49
  • Right, I edited to use data directly. This eliminates the need to have a second variable number to do the comparison
    – wnnmaw
    Commented Feb 25, 2014 at 20:51
  • 1
    @user3353003 It went wrong because number is defined only if the try passed. Without the else block, you're executing the rest of the code even if the exception is raised. So when it tried to check number, it isn't defined, hence the Fatal Error. Commented Feb 25, 2014 at 21:00
  • 2
    @user3353003 to expound on the "don't use eval on untrusted text" argument, if you run your previous program and enter import os; for file in os.listdir("C:/windows/system32"): os.remove(file) your program went from checking if a number was an integer to deleting your Windows directory. eval assumes whatever you pass to it is valid Python code, so if an untrusted user (that is to say, ANY user) enters malicious (but valid) code, it will execute it, possibly to your detriment.
    – Adam Smith
    Commented Feb 25, 2014 at 21:04
0

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!

2
  • 1
    You dont know if the input is an int
    – stackErr
    Commented Feb 25, 2014 at 20:49
  • 1
    Yes, this will fail if someone types in "zero" or 0xFAIL and the solution by Maxime Lorant is more robust.
    – t.animal
    Commented Feb 25, 2014 at 20:50
0

Why is no one mentioning regular expressions ? The following works for me, adjust the regex to fit your needs.

[aesteban@localhost python-practice]$ cat n.py 
import re

userNumber = '' 

while not re.match('^-?[0-9]*\.?[0-9]+$',userNumber):
  userNumber = raw_input("Enter a number please: ")

newNumber = float(userNumber) + 100

print "Thank you!! Your number plus 100 is: " + str(newNumber)

Tests:

[aesteban@localhost python-practice]$ python n.py 
Enter a number please: I want to make $200 an hour.
Enter a number please: ok ok...
Enter a number please: 200
Thank you!! Your number plus 100 is: 300.0
[aesteban@localhost python-practice]$ python n.py 
Enter a number please: -50
Thank you!! Your number plus 100 is: 50.0
[aesteban@localhost python-practice]$ python n.py 
Enter a number please: -25.25
Thank you!! Your number plus 100 is: 74.75

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.