To print the variable type in Python, you can use the type() function to get the type and print it with print()

a = 1
b = "string"
c = [0, 1, 2]
d = (0, 1, 2)
e = {"key":"value"}
f = 1.0
g = {"set"}

print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print(type(f))
print(type(g))

#Output:
<class 'int'>
<class 'str'>
<class 'list'>
<class 'tuple'>
<class 'dict'>
<class 'float'>
<class 'set'>

When working with different objects in Python, the ability to check the type of your variables and objects easily is very important.

In Python, you can easily get the variable type and print it.

What Types Are in Python for Print Variable Type?

Python is a dynamically typed language, which means that the type is interpreted at runtime. Variables in Python can belong to various data types. Some common variable types in Python include:

  1. Integers (int): Whole numbers without a decimal point.

  2. Floats (float): Numbers with a decimal point or numbers written in scientific notation.

     
  3. Strings (str): Sequences of characters enclosed in single or double quotes.

  4. Booleans (bool): Logical values representing True or False.

  5. Lists (list): Ordered collections of items. Items can be of different types.

  6. Tuples (tuple): Similar to lists but immutable (cannot be modified once created).

     
  7. Dictionaries (dict): Unordered collections of key-value pairs.

  8. Sets (set): Unordered collections of unique items.

  9. NoneType (None): Represents the absence of a value or a null value.

Not only is Python dynamically typed, meaning you don’t explicitly declare the variable type, but also the interpreter infers the type based on the value assigned to it. Additionally, Python supports type hints, which allow you to provide optional type information in your code for better readability and tools like linters and static analyzers.

type() is a built-in function that helps you find the class type of the given variable.

You can use the type() function to get the type and print it with print().

For example, below shows you how to print different objects in Python.

a = 1
b = "string"
c = [0, 1, 2]
d = (0, 1, 2)
e = {"key":"value"}
f = 1.0
g = {"set"}

print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print(type(f))
print(type(g))

#Output:
<class 'int'>
<class 'str'>
<class 'list'>
<class 'tuple'>
<class 'dict'>
<class 'float'>
<class 'set'>

Hopefully this article has been useful for you to learn how to print the type of a variable in Python.

 

Categorized in:

Python,

Last Update: March 1, 2024