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.
- isinstance() method
- is_integer() method
- type() method
- try except method
Python 3 isinstance() Examples
Example1
isinstance(5,int)
Example2
isinstance(5.5,int)
Example3
isinstance('hello',int)
Python 2 isinstance() Examples
Python 2 has two integer data types - int and long.
Example1
isinstance(long(5),(long))
isinstance(5,long)
isinstance(5,int)
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
x = 5.5
x.is_integer()
However is_integer() can be used for integers if we first convert integer to float as shown in example 2.
Example2
x = 5
float(x).is_integer()
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 usage is similar in both Python 2 and Python 3.
Example1
type(5)
We can use in code something like this...
Example2
x = 5
if type(x) is int:
print("%d is Integer"%x)
Well, try except can be used to catch anything in Python.
Example1
x = 5
try:
float(x)
print("%d is Integer"%x)
except ValueError:
print("%d is not Integer"%x)
Example2
x = 'Hello'
try:
float(x)
print("%d is Integer"%x)
except ValueError:
print("%s is not Integer"%x)
However above code will fail for following example.
Example3
x = 5.5
try:
float(x)
print("%s is Integer"%x)
except ValueError:
print("%s is not Integer"%x)
Let us fix the above code using try except.
Example4
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)
is_integer(5)
is_integer(5.5)
is_integer('hello')
Related Notebooks
- What is LeakyReLU Activation Function
- cannot access local variable a where it is not associated with a value but the value is defined
- Python Pandas String To Integer And Integer To String DataFrame
- How To Take Integer Input From Command Line In Python
- How to do SQL Select and Where Using Python Pandas
- Summarising Aggregating and Grouping data in Python Pandas
- Merge and Join DataFrames with Pandas in Python
- How to Convert Python Pandas DataFrame into a List
- How to Plot a Histogram in Python