473,573 Members | 2,719 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(2387482734 274)) and ...

but this seems kludgy. Any better way?

Thanks,
Rob
Jul 18 '05 #1
4 44146
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.e du> wrote in
news:ma******** *************** ***********@pyt hon.org:
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(2387482734 274)) 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.u k
int month(char *p){return(1248 64/((p[0]+p[1]-p[2]&0x1f)+1)%12 )["\5\x8\3"
"\6\7\xb\1\x9\x a\2\0\4"];} // Who said my code was obscure?
Jul 18 '05 #3

"Rob Hunter" <ro*@cs.brown.e du> wrote in message
news:ma******** *************** ***********@pyt hon.org...
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(2387482734 274)) 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(2387482734 274)) 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.