How to check if a variable is an integer in Python

We’ve listed below two different ways to check whether variable contains integer value or not.

  • Using type() function
    • It accepts operand(variable or value) as an argument and return it’s data-type.
    • Return value can be used to with int class.
  • Using isinstance() function
    • We pass first argument as operand(variable or value) and second argument as int class.

In this article we’ll see how to check if a variable is an integer. Let us understand also with an example.

Check Python variable is of an integer type or not

Method 1 using type() function

Passing the variable as an argument, and then comparing the result to the int class.

age = 12
type(age) == int
# True

age = 12.24
type(age) == int
# False

age = '12.24'
type(age) == int
# False

Method 2 using isinstance() function

Passing variable as first argument, and int class as second argument.

age = 12
isinstance(age, int)
# True

age = 12.24
isinstance(age, int)
# False

age = '12.24'
isinstance(age, int)
# False

Even comparing float type of value with int class, either by using type() or isinstance() function, will give False as resultant value. Same for value '12.24' enclosed in single quotes.

Hope you like this!

Keep helping and happy 😄 coding

Vishnu Damwala
Vishnu Damwala

A web geek, an industry experienced web developer & tutor/instructor residing in India 🇮🇳