free stats

How to check whether a variable is an integer or not in Python

Last Update : 15 Dec, 2022 Python, Programming, Example

In this tutorial, you will learn to check whether a variable is an integer or not in a Python program.

 

Check whether a variable is an integer or not by using isinstance() function

 

Here, you can use Python's built-in isinstance() function to check if a given variable is an integer or not. Also, this is the standard solution for checking whether a given variable is an integer or not.

This function returns True if the first argument is an instance of the second argument.

x = 10
y = "Some Text"
 
x_isInteger = isinstance(x, int)
print(x_isInteger)

y_isInteger = isinstance(y, int)
print(y_isInteger)

This program produces the following result -:

True
False

 

You can use the numbers.Integral Python class to check for an integer value.  Also, this is a usage of numeric abstract base classes instead of concrete classes to check for an integer value.

import numbers

x = 10
y = "Some Text"
 
x_isInteger = isinstance(x, numbers.Integral)
print(x_isInteger)

y_isInteger = isinstance(y, numbers.Integral)
print(y_isInteger)

This program produces the following result -:

True
False

 

You found this tutorial / article valuable? Need to show your appreciation? Here are some options:

01. Spread the word! Use following buttons to share this tutorial / article link on your favorite social media sites.

02. Follow us on Twitter, GitHub ,and Facebook.