Can You Check Data Type in Python?
In Python, you can check the data type of a variable or value using the type() function. This function returns the data type of the specified object. It is a useful tool for debugging and ensuring that your code is working with the correct data types.
Using the type() Function
The type() function takes an object as its parameter and returns its data type. Let’s take a look at some examples:
x = 5 print(type(x))
This will output <class ‘int’>, indicating that the variable x is of type integer.
y = "Hello, World!" print(type(y))
This will output <class ‘str’>, indicating that the variable y is of type string.
z = [1, 2, 3] print(type(z))
This will output <class ‘list’>, indicating that the variable z is of type list.
Determining Data Types for Built-in Functions and Modules
In addition to checking the data type of variables, you can also use the type() function to determine the data types of built-in functions and modules.
This will output:
<class 'builtin_function_or_method'> <class 'module'>
The first line indicates that len is a built-in function, and the second line indicates that math is a module.
Checking Data Types for User-Defined Objects
You can also use the type() function to check the data type of user-defined objects. When you create a class in Python, you are essentially creating a new data type. Let’s see an example:
class Person: def __init__(self, name, age): self.name = name self.age = age person = Person("John", 25) print(type(person))
This will output <class ‘__main__.Person’>, indicating that person is an instance of the Person class.
The type() function in Python allows you to check the data type of variables, values, built-in functions, modules, and user-defined objects. It is a powerful tool for debugging and ensuring that your code is working with the correct data types. By understanding how to use this function effectively, you can write more robust and error-free Python code.