Contrary to other programming languages, such as C++ or Java, you don’t specify the data type when defining a variable in Python, but it doesn’t mean that the variable doesn’t have a type.
You can check the variable type using the type function that returns the type of data.
Here’s how it works:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
a = 1 b = float(a) c = 1.45 d = 'text' e = '' f = None print(type(a)) print(type(b)) print(type(c)) print(type(d)) print(type(e)) print(type(f)) |
This code returns this result:
<class 'int'> <class 'float'> <class 'float'> <class 'str'> <class 'str'> <class 'NoneType'>
You can also check types of data structures. Here’s an example of a list, dictionary, and tuple.
1 2 3 4 5 6 7 |
my_list = ['cat', 4, 'emu', 'dog', '.'] my_dict = {'animal': 'chicken'} my_tuple = (5, 'test', 2) print(type(my_list)) print(type(my_dict)) print(type(my_tuple)) |
The result:
<class 'list'> <class 'dict'> <class 'tuple'>