开发者

Determining if an input is a number

How do I find out if my user's input is a number?

input = raw_input()

if input = "NUMBER":
    do this
else:
    do this

What is "NUMBER" in this case开发者_运维知识库?


Depends on what you mean by "number". If any floating point number is fine, you can use

s = raw_input()
try:
    x = float(s)
except ValueError:
    # no number
else:
    # number


If you're testing for integers you can use the isdigit function:

x = "0042"

x.isdigit()

True


string = raw_input('please enter a number:')

Checking if a character is a digit is easy once you realize that characters are just ASCII code numbers. The character '0' is ASCII code 48 and the character '9' is ASCII code 57. '1'-'8' are in between. So you can check if a particular character is a digit by writing:

validNumber=False

while not validNumber:

string = raw_input('please enter a number:')

i=0

validNumber=True

while i

if not (string[i]>='0' and string[i]<='9'):

validNumber=False

print 'You entered an invalid number. Please try again'

break

i=i+1


An answer I found elsewhere on StackOverflow [I forget where] gave the following code for checking if something was a number:

#This checks to see if input is a number
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜