How to find type of a variable in Python
Hi Coder! In this article, we will learn how to find the variable type in Python. Before going into the implementation part let us know a little about the type() function.
The type() function in Python
Syntax: type(object)
The type() function in Python takes an object as a parameter and returns the class type of the object.
Example:
Let n = 1 then
type(n) will return the integer class type.
Finding the type of a variable
Let us first declare a few variables/objects to find their class types.
- Integer
int_var = 100
- Float
float_var = 139.0
- String
string_var = "HelloWorld"
- Complex
complex_var = 7+2.0j
- Bool
bool_var = False
- List
list_object = [1,2,3,"CodeSpeedy"]
- Tuple
tuple_object = (1.0, 'Python')
- Set
set_object = {(2)}
- Dictionary
dictionary_object = {1:'Code',2:'Hello'}
- User-defined Class
Let us create a user-defined class and also create an object of it.class MyClass: pass MyClass_object = MyClass()
Python code to check data type of a variable
Now, let us try to print the types of all the objects that we created.
print(type(int_var)) print(type(float_var)) print(type(string_var)) print(type(complex_var)) print(type(bool_var)) print(type(list_object)) print(type(tuple_object)) print(type(set_object)) print(type(dictionary_object)) print(type(MyClass_object))
Program
class MyClass: pass int_var = 100 float_var = 139.0 string_var = "HelloWorld" complex_var = 7+2.0j bool_var = False MyClass_object = MyClass() list_object = [1,2,3,"CodeSpeedy"] tuple_object = (1.0,'Python') set_object = {(2)} dictionary_object = {1:'Code',2:'Hello'} print(type(int_var)) print(type(float_var)) print(type(string_var)) print(type(complex_var)) print(type(bool_var)) print(type(list_object)) print(type(tuple_object)) print(type(set_object)) print(type(dictionary_object)) print(type(MyClass_object))
Output
<class 'int'> <class 'float'> <class 'str'> <class 'complex'> <class 'bool'> <class 'list'> <class 'tuple'> <class 'set'> <class 'dict'> <class '__main__.MyClass'>
Yahoo! We have learned to find the type of variables in python. In case of any doubts feel free to post them below.
Also, do check out our other related articles:
Leave a Reply