isNumber? check

R

Rob Hunter

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
 
D

Duncan Booth

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.
 
T

Terry Reedy

Rob Hunter said:
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

But how about x=x-0?
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
 
M

Miki Tebeka

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top