1

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?

4 Answers 4

8

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 
Sign up to request clarification or add additional context in comments.

1 Comment

If you want to also support complex numbers, use complex(). For simple ints int() should suffice.
2

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

x = "0042" x.isdigit() 

True

2 Comments

Sadly enough, x = "0.5"; x.isdigit() == False. Not suitable for floats.
Also doesn't work for negative numbers and bases other than 10.
0

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

Comments

0

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.