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
intclass.
- Using
isinstance()function- We pass first argument as operand(variable or value) and second argument as
intclass.
- We pass first argument as operand(variable or value) and second argument as
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
Related Articles
Deepen your understanding with these curated continuations.
How to Display Multiplication Tables in Python
Learn to generate multiplication tables in Python using for loops and the range() function. A perfect exercise for beginners to master iterative logic.
How to Generate Random Numbers in Python: A Quick Guide
Learn how to generate random integers and floats in Python using the random library. Master randint() and random() functions with simple code examples.
Swapping Variable Values in Python
Discover multiple ways to swap the values of two variables in Python, including the elegant tuple unpacking method and the traditional third-variable approach.