How to check if Python Object is a Number ?
This tutorial guides you on how to check if Python Object is a Number using isinstance() built-in function. Let’s learn how to check if object is a number in Python with example.
Check if Python Object is a Number
Python isinstance() function syntax is as follows:
isinstance(object, classinfo)
The isinstance() function returns “true” if the object is instance of classinfo argument.
If the object is not an instance of classinfo argument or its subclass, then the function will return “false“.
Note, if the classinfo argument is a tuple of type objects. In that case, this function will return “true” if the object is an instance of any of the types.
And, if the classinfo is not a type or tuple of types, then TypeError exception will be raised.
For example,
import numbers [isinstance(n, numbers.Number) for n in (10, 10.5,10000000000000000000000000000000000000000000, 5+0j)]
Whereas,
- 10 is a int number.
- 10.5 is a floating point number.
- 10000000000000000000000000000000000000000000 is a long number.
- And 5+0j is a complex number.
Output
In the above example,
[True, True, True, True]
Python isinstance() Number
You can also check whether the object is of specific Number type like int, float, long etc., as shown below.
For example,
i = 5 print('i is int number:', isinstance(i, int)) f = 5.5 print('f is float number:', isinstance(f, float))
When you execute the above code, you will get the following output.
i is int number: True f is float number: True
Similarly, you could check whether Python Object is of type string, bytes, tuple, list etc.,
That’s it. You had learnt how to check if Python Object is a Number using isinstance() built in Python function.
Hope it helped 🙂
You’ll also like:
- Convert floating point number to fixed point in Python
- What is %matplotlib inline and how to use ?
- Increase the cell width of the Jupyter Notebook in browser
- Add python3 kernel to jupyter IPython notebook ?
- Reset jupyter notebook theme to default theme
- How to change the default theme in Jupyter Notebook ?
- Change the Jupyter Notebook startup folder in Windows & Mac
- To run Jupyter Notebook on Windows from command line
- Run a Jupyter Notebook .ipynb file from terminal or cmd prompt
- Amazon Linux AMI : apt-get command not found
- Linux: sudo: apt-get: command not found
- How to Start Stop Restart MariaDB on Linux OS ?
- Putty Fatal Error No supported authentication methods available
- Find which users belongs to a specific group in linux
- Embed HTML within IPython Notebook
- Python program to find the greatest of three numbers
- Is it possible to change Google Cloud Platform Project ID ?
- Error: helm install unknown flag: –name
- Install Python 3 on Windows 10 machine
- Convert negative to positive number in Python
- TypeError: a bytes-like object is required, not ‘str’ – Python3
- Extract numbers from a string in python