Test for number?

George Sakkis george.sakkis at gmail.com
Mon Sep 4 15:48:29 EDT 2006


Dr. Pastor 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
> ---
> Thanks for any guidance.

x=raw_input('\nType a number from 1 to 20')
try:
    x = int(x)
    if x<1 or x>20: raise ValueError()
except ValueError:
    Do_B
else:
    Do_A


If you want to distinguish between the two error cases (not a number vs
number not in [1,20]), handle the second one as "Do_C" instead of
raising ValueError.

HTH,
George




More information about the Python-list mailing list