Python – Verify type of an Object

Python – Verify Type of an Object

To verify the datatype of an object in Python, use type() builtin function. type() function takes the object as argument and returns a type object representing the type of the given object. And we can compare this type object with a datatype using is operator.

Check if Object is Integer

In the following program, we initialise a variable with integer value, and programmatically check if that object is integer or not.

Python Program

obj = 4
obj_type = type(obj)
if obj_type is int:
    print('Object is an integer.')
else:
    print('Object is not an integer.')
Run Code Copy

Output

Object is an integer.

Check if Object is String

In the following program, we initialise a variable with integer value, and programmatically check if that object is integer or not.

Python Program

obj = 'apple'
obj_type = type(obj)
if obj_type is str:
    print('Object is a string.')
else:
    print('Object is not a string.')
Run Code Copy

Output

Object is a string.

Similarly, we can check for other datatypes as well.

Related Tutorials

Code copied to clipboard successfully 👍