check if a number is int or float
I like @ninjagecko's answer the most.
This would also work:
for Python 2.x
isinstance(n, (int, long, float))
Python 3.x doesn't have long
isinstance(n, (int, float))
there is also type complex for complex numbers
Use isinstance
.
>>> x = 12
>>> isinstance(x, int)
True
>>> y = 12.0
>>> isinstance(y, float)
True
So:
>>> if isinstance(x, int):
print('x is a int!')
x is a int!
In case of long integers, the above won't work. So you need to do:
>>> x = 12L
>>> import numbers
>>> isinstance(x, numbers.Integral)
True
>>> isinstance(x, int)
False
(note: this will return True
for type bool
, at least in cpython, which may not be what you want. Thank you commenters.)
One-liner:
isinstance(yourNumber, numbers.Real)
This avoids some problems:
>>> isinstance(99**10,int)
False
Demo:
>>> import numbers
>>> someInt = 10
>>> someLongInt = 100000L
>>> someFloat = 0.5
>>> isinstance(someInt, numbers.Real)
True
>>> isinstance(someLongInt, numbers.Real)
True
>>> isinstance(someFloat, numbers.Real)
True