How to check data type in python?
With Python's built-in type() method, you may determine a variable's type. The type() function returns the data type of a variable as a string.
Here's an example of how to use the type() function:
In this example, we create a variable x and assign it the value 5. After that, we call the type() function with x as its argument, which returns <class 'int'>. It tells us that x is an integer.
Here's a more detailed explanation of how the type() function works:
When you call type() with a variable as its argument, Python looks at the value of the variable and determines its data type. There are numerous built-in data types in Python, including:
The type() function returns a string that represents the data type of the variable. For example, if you pass an integer variable to type(), it will return the string <class 'int'>.
Here are some examples of using type() to check the type of different variables:
Using isinstance() function
In Python, you can also use the isinstance() function to check whether a variable is of a certain type. The isinstance() function takes two arguments: the variable you want to check, and the type you want to check for. It returns True if the variable is of the specified type, and False otherwise.
Here's an example of how to use the isinstance() function
In this example, we create a variable x and assign it the value 5. After that, we call the isinstance() function with x as the first argument and the int type as the second argument. The function returns True, indicating that x is an integer.
You can also use the type() and isinstance() functions to check if a variable is a subclass of a particular type. The characteristics and methods of the parent class are inherited by the subclass, which is a more specialized version of the class.Here's an example:
<class '__main__.Dog'> True
This example defines a class Animal with a constructor that takes a name argument. After that, we define a subclass Dog that inherits from Animal and has an additional bark() method. We create an instance of Dog called my_dog.
We can use the type() function to check that my_dog is an instance of the Dog class, and the isinstance() function to check that my_dog is also an instance of the Animal class (since Dog is a subclass of Animal).
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week