Check if Python Object is a Number

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

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:

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments