Last updated: Apr 9, 2024
Reading timeยท8 min
Use the isinstance()
function to check if a number is an int or float.
The isinstance
function will return True
if the passed-in object is an
instance of the provided class (int
or float
).
my_num = 1357 if isinstance(my_num, int): print('number is int') if isinstance(my_num, float): print('number is float') # ----------------------------------- # โ checks if a number is either int or float if isinstance(my_num, (int, float)): print('Number is either int or float')
We used the isinstance()
function to check if a number is an int
or a
float
.
The isinstance
function returns True
if the passed-in object is an instance or a subclass of
the passed-in class.
print(isinstance(357, int)) # ๐๏ธ True print(isinstance(357, float)) # ๐๏ธ False print(isinstance(3.14, float)) # ๐๏ธ True print(isinstance(3.14, int)) # ๐๏ธ False
The isinstance()
function correctly returns whether the passed-in object is an
instance or a subclass of the provided class.
However, there is an edge case - booleans are also an instance of integers.
print(isinstance(True, int)) # ๐๏ธ True print(isinstance(False, int)) # ๐๏ธ True
This is because the bool
class is a subclass of
int.
If you need to check if a number is either int or float, pass a tuple
containing the int
and float
classes in the call to the isinstance()
function.
my_num = 1357 if isinstance(my_num, (int, float)): # ๐๏ธ this runs print('Number is either int or float')
isinstance
function takes can be a class or a tuple containing multiple classes.The call to the function above checks if the passed-in object is either an int
or a float
.
Using a tuple
in the call to the function is equivalent to using two calls
with the OR
operator.
my_num = 1357 if isinstance(my_num, int) or isinstance(my_num, float): print('Number is either int or float')
If you just want to print the type of the number, use the type()
class.
my_num = 1357 print(type(my_num)) # ๐๏ธ <class 'int'> my_num_2 = 3.14 print(type(my_num_2)) # ๐๏ธ <class 'float'>
The type class returns the type of an object.
Most commonly the return value is the same as accessing the __class__
attribute on the object.
To check if a string is an integer or a float:
str.isdigit()
method to check if every character in the string is a
digit.True
, the string is an integer.False
, the string is a floating-point number.my_str = '2468' if my_str.isdigit(): my_num = int(my_str) print('String is an integer') else: my_num = float(my_str) print('String is a float') print(my_num) # ๐๏ธ 2468
try/except
solution.We used the str.isdigit()
method to check if all characters in the string are
digits.
The str.isdigit method returns
True
if all characters in the string are digits and there is at least 1
character, otherwise False
is returned.
The str.isdigit()
metho would return False
if the string has a decimal point
or starts with a minus -
(is a negative number).
print('-123'.isdigit()) # ๐๏ธ False print('1.23'.isdigit()) # ๐๏ธ False
If you don't have to handle negative numbers, use the str.isdigit()
method as
it is sufficient.
If you have to handle negative numbers, use a try/except block.
try/except
This is a three-step process:
int()
class in a try
block.int()
class succeeds, the string is an integer.except
block runs, the string is a floating-point number.my_str = '-2468' try: my_num = int(my_str) # ๐๏ธ this runs print('String is an integer') except ValueError: my_num = float(my_str) print('String is a float') print(my_num) # ๐๏ธ -2468
We used a try/except
statement to check if a string is an integer or a float.
If the try
block runs successfully, the string is an integer.
If calling the int()
class with the string raises a ValueError
, the except
block is run and the string is a floating-point number.
Unlike the str.isdigit()
method, this approach also handles negative numbers.
try/except
statement in this manner is commonly known as "asking for forgiveness rather than permission".We pass the string to the int()
class not knowing whether the conversion will
be successful, and if a ValueError
error is raised, we handle it in the
except
block.
To check if a string can be converted to an integer:
int()
class in a try/except
block.try
block will fully run.ValueError
in the except
block.def can_convert_to_int(string): try: int(string) return True except ValueError: return False print(can_convert_to_int('1357')) # ๐๏ธ True print(can_convert_to_int('-1357')) # ๐๏ธ True print(can_convert_to_int('1.357')) # ๐๏ธ False print(can_convert_to_int('ABC123')) # ๐๏ธ False
We used a try/except
block to check if a string can be converted to an
integer.
try
block succeeds, the function returns True
and the string can be converted to an integer.If calling the int()
class with the string fails, a ValueError
is raised and
the function returns False
.
try/except
statement in this manner is commonly known as "asking for forgiveness rather than permission".We pass the string to the int()
class not knowing whether the conversion will
be successful, and if a ValueError
error is raised, we handle it in the
except
block.
Alternatively, you can use the str.isdigit()
method.
If the str.isdigit
method returns True
, then all of the characters in the
string are digits and it can be converted to an integer.
my_str = '1357' if my_str.isdigit(): my_int = int(my_str) print(my_int) # ๐๏ธ 1357 print('โ string can be converted to integer') else: print('โ๏ธ string CANNOT be converted to integer')
We used the str.isdigit()
method to check if a string can safely be converted
to an integer.
The str.isdigit method returns
True
if all characters in the string are digits and there is at least 1
character, otherwise False
is returned.
The method checks if all characters in the string are digits, so if the string
had a minus sign or a decimal, it would return False
.
my_str = '-1357' if my_str.isdigit(): my_int = int(my_str) print(my_int) print('โ string can be converted to integer') else: # ๐๏ธ this runs print('โ๏ธ string CANNOT be converted to integer')
try/except
example instead, as it also covers negative integers.If you just want to try converting the string to an integer and silence/ignore
the ValueError
if the conversion fails, use a pass
statement.
my_str = '2468' try: my_int = int(my_str) print(my_int) # ๐๏ธ 2468 except ValueError: pass
The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.
class Employee: pass
To check if a string can be converted to a float:
float()
class in a try/except
block.try
block runs successfully, the string can be converted to a float.except
block runs, the string cannot be converted to a float.my_str = '3.456' try: result = float(my_str) print(result) # ๐๏ธ 3.456 except ValueError: print('Value cannot be converted to a float')
We used a try/except
statement to check if a string can be converted to a
float.
If the try
block runs successfully, the string can be converted to a float.
float()
raises a ValueError
, the string cannot be converted to a float.my_str = 'abc1.23' try: result = float(my_str) print(result) except ValueError: # ๐๏ธ this runs print('Value cannot be converted to a float')
You can also extract the logic into a reusable function.
def can_convert_to_float(string): try: result = float(string) print(result) return True except ValueError: return False print(can_convert_to_float('123')) # ๐๏ธ True print(can_convert_to_float('1.23')) # ๐๏ธ True print(can_convert_to_float('a.bc')) # ๐๏ธ False print(can_convert_to_float('.5')) # ๐๏ธ True if can_convert_to_float('3.14'): # ๐๏ธ this runs print('String can be converted to a float โ ') else: print('String cannot be converted to a float โ๏ธ')
If the try
block succeeds, the function returns True
.
If calling the float() class with the string fails,
a ValueError
is raised and the function returns False
.
try/except
statement in this manner is commonly known as "asking for forgiveness rather than permission".We pass the string to the float()
class not knowing whether the conversion
will be successful, and if a ValueError
error is raised, we handle it in the
except
block.
If you want to silence/ignore the error when it's raised, use the pass
statement.
my_str = 'ab.cd' try: result = float(my_str) print(result) except ValueError: pass
The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.
You can use the float.is_integer()
method to check if a float is a whole
number.
import math # โ Check if a float is a whole number using float.is_integer() result = (3.00).is_integer() print(result) # ๐๏ธ True
The first example uses the float.is_integer()
method to check if a float is a
whole number.
The float.is_integer method returns a boolean result:
True
if the floating-point number is a finite, whole numberFalse
if it isn'tprint((3.00).is_integer()) # ๐๏ธ True print((3.14).is_integer()) # ๐๏ธ False
Alternatively, you can use the modulo operator.
This is a three-step process:
1
.0
, the number is whole.0
, the number has a decimal point.num = 5.00 result = num % 1 == 0 print(result) # ๐๏ธ True
The modulo (%) operator returns the remainder from the division of the first value by the second.
print(10 % 1) # ๐๏ธ 0 print(10.5 % 1) # ๐๏ธ 0.5
If the remainder we get from dividing the number by 1
is 0
, then we have a
whole number.
Conversely, if there is a remainder from dividing by 1
, the number has a
decimal point.
Alternatively, you can use the math.floor()
method.
This is a three-step process:
math.floor()
method.math.floor()
method will round the number down.import math num = 7.00 result = math.floor(num) == num print(result) # ๐๏ธ True
The math.floor method returns the largest integer less than or equal to the provided number.
print(math.floor(3.99)) # ๐๏ธ 3 print(math.floor(3.00)) # ๐๏ธ 3
If the rounded-down number is equal to the number itself, then we have a whole number.
If the rounded-down number is different, the number has a decimal point.
You can learn more about the related topics by checking out the following tutorials: