How To Know Data Type In Python

Python is a dynamically-typed programming language, which means that you don’t have to explicitly specify the data type of a variable when you declare it. While this provides flexibility and ease of use, it can sometimes make it difficult to determine the data type of a variable during runtime.

In this post, we will discuss a few methods to find out the data type of a variable in Python.

1. Using the type() Function

The built-in type() function in Python can be used to determine the data type of a variable. The syntax of the type() function is as follows:

type(object)

It takes an object (a variable in our case) as input and returns its data type as output. Here’s an example:

num = 42
print(type(num))
# Output:

The type() function returns a class object, which represents the data type of the given variable. In the example above, it returned ‘int’ as the data type of the variable num.

2. Using the isinstance() Function

If you want to check if a variable belongs to a specific data type, you can use the built-in isinstance() function in Python. The syntax of the isinstance() function is as follows:

isinstance(object, classinfo)

It takes an object (a variable) and a classinfo (a data type) as inputs and returns True if the object is an instance of the specified data type, otherwise it returns False. Here’s an example:

num = 42
is_int = isinstance(num, int)
print(is_int)
# Output: True

In the example above, the isinstance() function checks if the variable num is an instance of the int data type and returns True.

3. Combining type() and isinstance()

You can also use a combination of type() and isinstance() functions to get more information about the data type of a variable. Here’s an example:

num = 42

if isinstance(num, int):
print(“Data type:”, type(num))
else:
print(“Not an integer”)
# Output: Data type:

In the example above, we first check if the variable num is an instance of the int data type using the isinstance() function. If it is, we print its data type using the type() function.

Conclusion

In this post, we discussed how to determine the data type of a variable in Python using the type() function, the isinstance() function, and a combination of both. By using these methods, you can easily find out the data type of a variable during runtime and make your code more robust and reliable.