Python is a dynamically typed programming language, meaning that the data type of a variable can change at runtime.
It is important to know the data type of a variable in order to perform operations on it effectively.
In this tutorial, we’ll learn how to determine the type of a variable in Python.
Method 1: Using the type Function
The simplest way to determine the type of a variable in Python is by using the built-in type function.
The type function returns the data type of the input argument as a type object.
Example:
x = 10 print(type(x)) # Output: <class 'int'> y = "Hello, World!" print(type(y)) # Output: <class 'str'> z = [1, 2, 3] print(type(z)) # Output: <class 'list'>
Method 2: Using the isinstance Function
Another way to determine the type of a variable in Python is by using the built-in isinstance function.
The isinstance function takes two arguments: the variable and the data type to be checked.
It returns a boolean value indicating whether the variable is an instance of the specified data type.
Example:
x = 10 print(isinstance(x, int)) # Output: True print(isinstance(x, str)) # Output: False y = "Hello, World!" print(isinstance(y, str)) # Output: True print(isinstance(y, list)) # Output: False z = [1, 2, 3] print(isinstance(z, list)) # Output: True print(isinstance(z, tuple)) # Output: False
Conclusion
In this post, we learned about two methods to determine the type of a variable in Python: using the type function and using the isinstance function.
Understanding the data type of a variable is an important aspect of programming, and these functions make it easy to determine the type in Python.