How to Check If a Variable Is an Integer or Float in Python
In Python, numerical data is typically represented as integers (int) or floating-point numbers (float). Distinguishing between these two types is essential for data validation, control flow, and ensuring mathematical precision.
This guide covers how to check if a number is an integer using isinstance() and the type() function, and explains the subtle differences between them.
Understanding int vs. float
int: Whole numbers without a fractional component (e.g.,10,-5,0).float: Numbers with decimal points or scientific notation (e.g.,10.0,3.14,1e5).
Even if a float represents a whole number (like 10.0), its data type is distinct from int (like 10).
Method 1: Using isinstance() (Recommended)
The standard, "Pythonic" way to check variable types is using isinstance(). It supports inheritance, meaning it will also return True for subclasses of int (though usually not relevant for basic numbers).
num1 = 42
num2 = 42.0
# ✅ Correct: Check if num1 is an integer
if isinstance(num1, int):
print(f"{num1} is an Integer.")
else:
print(f"{num1} is NOT an Integer.")
# Check num2
if isinstance(num2, int):
print(f"{num2} is an Integer.")
else:
print(f"{num2} is NOT an Integer (it is a {type(num2).__name__}).")
Output:
42 is an Integer.
42.0 is NOT an Integer (it is a float).
Method 2: Using type() (Strict Checking)
If you need to ensure a variable is exactly an integer and not a subclass, use type().
x = 100
# ✅ Correct: Strict type checking
if type(x) is int:
print("x is strictly an int.")
isinstance() vs type(): isinstance(True, int) returns True because bool is a subclass of int. type(True) is int returns False. In most cases, isinstance is preferred, but be aware of booleans.
Checking if a Float is Integrally Equivalent
Sometimes you have a float (like 5.0) and you want to know if it represents an integer value mathematically, even if the data type is float. You can use the float.is_integer() method.
val1 = 5.0
val2 = 5.5
# Check if float values are integers mathematically
print(f"{val1} is integer-like? {val1.is_integer()}")
print(f"{val2} is integer-like? {val2.is_integer()}")
Output:
5.0 is integer-like? True
5.5 is integer-like? False
Conclusion
To check if a number is an integer in Python:
- Use
isinstance(x, int)to check the variable's data type. This is the standard approach. - Use
type(x) is intif you need strict type checking (e.g., to exclude booleans). - Use
x.is_integer()ifxis a float and you want to check if it has no decimal part.