The Number. isInteger() method returns true if a value is an integer of the datatype Number. Otherwise it returns false .
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!
EDIT:
As pointed out, 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
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
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
It's easier to ask forgiveness than ask permission. Simply perform the operation. If it works, the object was of an acceptable, suitable, proper type. If the operation doesn't work, the object was not of a suitable type. Knowing the type rarely helps.
Simply attempt the operation and see if it works.
inNumber = somenumber
try:
inNumberint = int(inNumber)
print "this number is an int"
except ValueError:
pass
try:
inNumberfloat = float(inNumber)
print "this number is a float"
except ValueError:
pass
What you can do too is usingtype()
Example:
if type(inNumber) == int : print "This number is an int"
elif type(inNumber) == float : print "This number is a float"
You can use modulo to determine if x is an integer numerically. The isinstance(x, int)
method only determines if x is an integer by type:
def isInt(x):
if x%1 == 0:
print "X is an integer"
else:
print "X is not an integer"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With