Test for number?

Tim Williams tim at tdw.net
Mon Sep 4 14:25:11 EDT 2006


On 04/09/06, Dr. Pastor <elpX at adsihqx.com> wrote:
> In the following code I would like to ascertain
> that x has/is a number. What the simplest TEST should be?
> (Could not find good example yet.)
> ---
> x=raw_input('\nType a number from 1 to 20')
> if TEST :
>                 Do_A
> else:
>                 Do_B
> ---

Something simple like the following might help,

>>> def numtest():
... 	x=raw_input('\nType a number from 1 to 20')
... 	try:
... 		x=int(x)
... 		print x, "is a number between 1 & 20 "
... 	except:
... 		print x, "is not a number"
...
>>> numtest()   # enter 1
1 is a number between 1 & 20
>>> numtest()  #  enter "f"
f is not a number

its not a final solution though,  think input = -2, 5.5  or 21

HTH :)



More information about the Python-list mailing list