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 complex(). For simple ints int() should suffice.If you're testing for integers you can use the isdigit function:
x = "0042" x.isdigit() True
x = "0.5"; x.isdigit() == False. Not suitable for floats.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