A2oz

How Do You Print Data Type in Python?

Published in Python Programming 2 mins read

In Python, you can't directly print the data type of a variable. However, you can use the built-in type() function to determine the data type and then print it. Here's how:

1. Using the type() Function

The type() function takes a variable as input and returns its data type. You can then use the print() function to display this information.

my_variable = 10
data_type = type(my_variable)
print(data_type)  # Output: <class 'int'>

In this example, my_variable is an integer, so the type() function returns <class 'int'>.

2. Direct Printing with type()

You can also combine the type() function with print() in a single line:

my_variable = "Hello"
print(type(my_variable))  # Output: <class 'str'>

This code will print the data type of my_variable, which is a string (<class 'str'>).

3. Printing Data Type and Value

To print both the data type and the value of a variable, you can use string formatting:

my_variable = 3.14
print(f"The data type of {my_variable} is {type(my_variable)}")
# Output: The data type of 3.14 is <class 'float'>

This code prints a formatted string that includes both the value (3.14) and the data type (<class 'float'>).

4. Practical Insights

Knowing the data type of a variable is crucial for performing accurate operations. For example, you can't add a string to an integer without converting one of them to a compatible data type.

5. Example

age = 25
name = "John"
is_student = True

print(f"Age: {age} ({type(age)})")
print(f"Name: {name} ({type(name)})")
print(f"Is Student: {is_student} ({type(is_student)})")

# Output:
# Age: 25 (<class 'int'>)
# Name: John (<class 'str'>)
# Is Student: True (<class 'bool'>)

This code demonstrates how to print data types for different types of variables.

Conclusion

By using the type() function, you can easily determine and print the data type of any variable in Python. This information is crucial for understanding how your code works and ensuring that you perform operations correctly.

Related Articles