Table of Contents
What is the type of variable in Python?
We use variables to store data in a reserved memory location. The type of a variable defines the memory allocated to it. The type of a variable is based on the data we store in it. We do not need to explicitly mention the type of a variable while declaring it in Python. Some of the data types in Python are int
, float
, str
, and more.
Ways to print type of variable in Python
In this tutorial, we will print type of variable in Python using different methods.
Using the type()
function
We can use the type()
function to return the data type of an object in Python. It is a built-in function.
For example,
1 2 3 4 5 6 |
a = "Manav" b = 5.2 print(type(a)) print(type(b)) |
Output:
In the above example,
- We declare a variable
a
that contains a string and another variableb
that stores a floating value. - The
type()
function tells the data type of these variables. - We display these values using the
print()
function.
Using the isinstance()
function
We use the isinstance()
function to check whether a variable belongs to a given data type or not. We pass the variable and the data type within the function, and it will return True if the type of the variable matches the given data type.
See the code below.
1 2 3 4 5 6 |
a = "Manav" b = 5.2 print(isinstance(a, str)) print(isinstance(b, int)) |
Output:
False
In the above example,
- The variable
a
is a string, so theisinstance(a,str)
returns True. - The variable
b
is a float value, so theisinstance(b,int)
returns False.
Using the __class__()
function
Functions that begin with an underscore are called magic functions in Python. It is not advisable to invoke such functions directly in Python.
The __class__
property returns the type or class of the given object.
For example,
1 2 3 4 5 6 |
a = "Manav" b = 5.2 print(a.__class__) print(b.__class__) |
Output:
Further reading:
Conclusion
In this tutorial, we discussed several methods to print the type of a variable in Python. The type()
, isinstance()
, and __Class__
methods return the type of a variable and we display it using the print()
function.
That’s all about how to print type of variable in Python.