Check whether a variable is an integer or not in Python
This post will discuss how to check whether a variable is an integer or not in Python.
1. Using isinstance() function
The standard solution to check if a given variable is an integer or not is using the isinstance() function. It returns True if the first argument is an instance of the second argument.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': x = 10 isInt = isinstance(x, int) print(isInt) # True |
You can also use numeric abstract base classes instead of concrete classes. To check for an integer value, you can use the numbers.Integral Python class:
|
1 2 3 4 5 6 7 8 9 |
import numbers if __name__ == '__main__': x = 10 isInt = isinstance(x, numbers.Integral) print(isInt) # True |
2. Using float.is_integer() function
If you need to consider floats with all zeros after the decimal point, consider using the float.is_integer() function. It returns True if the float instance is finite with integral value and False otherwise.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': x = 10.0 isInt = float(x).is_integer() print(isInt) # True |
3. Using int() function
Finally, you can use the int constructor to check for integral values. The function int(x) converts the argument x to an integer. If x is already an integer or a float with integral value, then the expression int(x) == x will hold true.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': x = 10.0 isInt = int(x) == x print(isInt) # True |
That’s all about determining whether a variable is an integer or not in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)