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:

Output:

<class 'int'>

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:

  • int: integers (whole numbers)
  • float: floating-point numbers (decimal numbers)
  • bool: boolean values (True or False)
  • str: strings (sequences of characters)
  • list: lists (ordered collections of values)
  • tuple: tuples (ordered collections of values, like lists but immutable)
  • dict: dictionaries (unordered collections of key-value pairs)
  • set: sets (unordered collections of unique values)

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

Output:

True

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:

Output:

<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).






Latest Courses