Check if a number is an int or float in Python

avatar

Borislav Hadzhiev

Last updated: Jul 13, 2022

banner

Photo from Unsplash

Check if a number is an int or float in Python #

Use the isinstance() function to check if a number is an int or float, e.g. if isinstance(my_num, int):. The isinstance function will return True if the passed in object is an instance of the provided class (int or float).

main.py
my_num = 1357 if isinstance(my_num, int): print('number is int') if isinstance(my_num, float): print('number is float') # ----------------------------------- # ✅ checks if 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.

main.py
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.
main.py
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.

main.py
my_num = 1357 if isinstance(my_num, (int, float)): # 👇️ this runs print('Number is either int or float')
The second argument the 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.

main.py
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.

main.py
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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.