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 with 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 with 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
In this case, only the type is checked, so you cannot check if a float
value is an integer (i.e., if the 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 float
is an integer: is_integer()
float
has the is_integer()
method that 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 an integer number (int
or integer float
). This function returns False
for a string (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 represents an integer
If you want to check if a numeric string represents an integer value, you can use the following function.
This function attempts to convert the value to float
using float()
. If the conversion is 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 details on converting strings to numbers and handling exceptions with try ... except ...
.