w3resource

How do you check the type of a variable in Python?

Python Variable Type Checking: Methods & Examples

In Python, we can check the type of a variable during runtime using various methods and built-in functions. Here are some common ways to determine a variable's data type:

Using the type() function:

The type() function returns the data type of an object as a type object.

Code:

temp1 = 42
temp2 = "Good Morning!"
print(type(temp1))
print(type(temp2))

Output:

<class 'int'>
<class 'str'>

Using isinstance() function:

The isinstance() function checks if a variable is an instance of a specified class or data type.

Code:

n = 12.23
if isinstance(n, float):
    print("n is a float.")
else:
    print("n is not a float.")

Output:

n is a float.

Using type() and __name__:

We can use the type() function along with the __name__ attribute of the type object to get the data type name as a string.

Code:

nums = [1, 2, 3]
print(type(nums).__name__)

Output:

list

Using the str() function:

The str() function can be used to get a human-readable string representation of the data type of a variable.

Code:

x = 22.7
print("The data type of x is:", str(type(x)))

Output:

The data type of x is: <class 'float'>

Using the type() function for type comparison:

You can compare the type() function result with known Python data types directly.

Code:

s = "Good Morning!"
if type(s) == str:
    print("s is a string.")
else:
    print("s is not a string.")

Output:

 s is a string.

Using the class attribute:

The class attribute can be used to get the class of user-defined objects, and then the name attribute can be used to get their names.

Code:

class Temp:
    pass
obj = Temp()
print(obj.__class__.__name__)

Output:

Temp


Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-interview/how-do-you-check-the-type-of-a-variable-in-python.php