Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
115 views
in Technique[技术] by (71.8m points)

Python check for integer input

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...