Check If a Number Is an Integer in Python
This article explains how to check if a number is an integer or has a fractional part in Python.
See the following article to learn how to obtain the fractional and integer parts of a number.
See the following article to check if a string is a number.
Check if an object is int
or float
: isinstance()
You can get the type of an object using the built-in type()
function.
i = 100
f = 1.23
print(type(i))
print(type(f))
# <class 'int'>
# <class 'float'>
You can also check if an object is of a specific type using the built-in isinstance()
function.
print(isinstance(i, int))
# True
print(isinstance(i, float))
# False
print(isinstance(f, int))
# False
print(isinstance(f, float))
# True
Since this approach only checks the type, it cannot determine whether a float
value represents an integer (i.e., whether its fractional part is 0
).
f_i = 100.0
print(type(f_i))
# <class 'float'>
print(isinstance(f_i, int))
# False
print(isinstance(f_i, float))
# True
Check if a float
value is an integer: is_integer()
The float
type provides an is_integer()
method, which returns True
if the value is an integer and False
otherwise.
f = 1.23
print(f.is_integer())
# False
f_i = 100.0
print(f_i.is_integer())
# True
For example, you can define a function that returns True
for integer values (int
or float
with no fractional part). This function returns False
for non-numeric types, such as strings (str
).
def is_integer_num(n):
if isinstance(n, int):
return True
if isinstance(n, float):
return n.is_integer()
return False
print(is_integer_num(100))
# True
print(is_integer_num(1.23))
# False
print(is_integer_num(100.0))
# True
print(is_integer_num('100'))
# False
Check if a numeric string is an integer
To check if a numeric string represents an integer value, you can use the following function.
This function attempts to convert the input to a float
. If successful, it calls the is_integer()
method and returns the result.
def is_integer(n):
try:
float(n)
except ValueError:
return False
else:
return float(n).is_integer()
print(is_integer(100))
# True
print(is_integer(100.0))
# True
print(is_integer(1.23))
# False
print(is_integer('100'))
# True
print(is_integer('100.0'))
# True
print(is_integer('1.23'))
# False
print(is_integer('string'))
# False
See the following articles for more details on converting strings to numbers and handling exceptions using try ... except ...
.