Check if a number is int or float

Here's how I did it:

inNumber = somenumber
inNumberint = int(inNumber)
if inNumber == inNumberint:
    print "this number is an int"
else:
    print "this number is a float"

Something like that.
Are there any nicer looking ways to do this?


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


(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

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"