472,334 Members | 1,507 Online

# isNumber? check

How do I check if a value is a number in Python?

One way is (x == type(1)) and (x == type(1.2)) and (x ==
type(2387482734274)) and ...

but this seems kludgy. Any better way?

Thanks,
Rob
Jul 18 '05 #1
4 43983
Rob Hunter wrote:
How do I check if a value is a number in Python?

isinstance(1+1j, (float,int,long,complex))

True

Peter

Jul 18 '05 #2
Rob Hunter <ro*@cs.brown.edu> wrote in
news:ma**********************************@python.o rg:
How do I check if a value is a number in Python?

One way is (x == type(1)) and (x == type(1.2)) and (x ==
type(2387482734274)) and ...

but this seems kludgy. Any better way?

Thanks,
Rob

If you really have to test it then use:

isinstance(x, (int, long, float, complex))

but mostly you shouldn't care.

--
Duncan Booth du****@rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
Jul 18 '05 #3

"Rob Hunter" <ro*@cs.brown.edu> wrote in message
news:ma**********************************@python.o rg...
How do I check if a value is a number in Python?

One way is (x == type(1)) and (x == type(1.2)) and (x ==
type(2387482734274)) and ...

but this seems kludgy. Any better way?

type(x) in (int, long, float, complex) # or,
isinstance(x, (int, long, float, complex)) # now preferred, I think

This also accepts a user-defined number-class instance.

This option gets to the point that 'number' is not exactly defined in
either Python or mathematics. So checking for 'numberness' may or may
not be what you need .

Terry J. Reedy
Jul 18 '05 #4
Hello Rob,
How do I check if a value is a number in Python?

One way is (x == type(1)) and (x == type(1.2)) and (x ==
type(2387482734274)) and ...

but this seems kludgy. Any better way?

Same thing, different way:
from types import IntType, LongType, FloatType
def is_num(n):
return n in (IntType, LongType, FloatType)

HTH.
Miki
Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.