Python print type of variable | Example code

Use the Python type() built-in function to check the variable type and after that show the result in the console with the help of the print method.

type(object)

If want to check if a variable is of a given type, use the isinstance method.

isinstance(object, classtype)

How to determine a Python variable’s type Example

Python simple example code gets the type of variable and prints it.

Example of type()

Check string, number, float, a complex number, list, tuple, dict, and set.

str1 = "Hello World"
age = 50
pi = 3.14
c_num = 3j + 10
my_list = ["A", "B", "C", "D"]
my_tuple = ("A", "B", "C", "D")
my_dict = {1: "a", 2: "b", 3: "c", 4: "d"}
my_set = {'A', 'B', 'C', 'D'}

print(type(str1))
print(type(age))
print(type(pi))
print(type(c_num))
print(type(my_list))
print(type(my_tuple))
print(type(my_dict))
print(type(my_set))

Output:

Python print type of variable

Example isinstance() String check

Python isinstance() takes in two arguments, and it returns true if the first argument is an instance of the class info given as the second argument.

message = isinstance("Hello World", str)
print(message)

Output: True

Do comment if you have any doubts and suggestions on this Python variable topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.