Python Is Integer

This notebook explains how to check in Python if a number is a integer.

There are multiple ways to check for integer in Python 2 and Python 3.

  1. isinstance() method
  2. is_integer() method
  3. type() method
  4. try except method

Python isinstance

Python 3 isinstance() Examples

Example1

In [2]:
isinstance(5,int)
Out[2]:
True

Example2

In [3]:
isinstance(5.5,int)
Out[3]:
False

Example3

In [4]:
isinstance('hello',int)
Out[4]:
False

Python 2 isinstance() Examples

Python 2 has two integer data types - int and long.

Example1

In [7]:
isinstance(long(5),(long))
Out[7]:
True
In [8]:
isinstance(5,long)
Out[8]:
False
In [9]:
isinstance(5,int)
Out[9]:
True

is_integer Python

is_integer is similar in both Python 2 and Python 3.

is_integer Python is for float numbers. It checks whether a float number is an integer.

Example1

In [6]:
x = 5.5
x.is_integer()
Out[6]:
False

However is_integer() can be used for integers if we first convert integer to float as shown in example 2.

Example2

In [7]:
x = 5
float(x).is_integer()
Out[7]:
True

Note: You can't use float(x).is_integer() standalone. You will need to use it inside try except as it is discussed later in this notebook.

Python type

Python type usage is similar in both Python 2 and Python 3.

Example1

In [8]:
type(5)
Out[8]:
int

We can use in code something like this...

Example2

In [9]:
x = 5
if type(x) is int:
    print("%d is Integer"%x)
5 is Integer

Check Integer using try except in Python

Well, try except can be used to catch anything in Python.

Example1

In [17]:
x = 5
try:
    float(x)
    print("%d is Integer"%x)
except ValueError:
    print("%d is not Integer"%x)
5 is Integer

Example2

In [16]:
x = 'Hello'
try:
    float(x)
    print("%d is Integer"%x)
except ValueError:
    print("%s is not Integer"%x)
Hello is not Integer

However above code will fail for following example.

Example3

In [32]:
x = 5.5
try:
    float(x)
    print("%s is Integer"%x)
except ValueError:
    print("%s is not Integer"%x)
5.5 is Integer

Let us fix the above code using try except.

Example4

In [28]:
def is_integer(x):
    try:
        float(x)
    except ValueError:
        print("%s is not Integer"%x)
    else:
        if float(x).is_integer():
            print("%d is Integer"%x)
        else:
            print("%f is not Integer"%x)
        
In [34]:
is_integer(5)
is_integer(5.5)
is_integer('hello')
5 is Integer
5.500000 is not Integer
hello is not Integer