In Python, you can check the data type of a variable or value using the type() function. The syntax to check the data type in Python is as follows:
Syntax:
type(value)
The type() function takes a single argument, which can be any variable or value that you want to check the data type of. It returns the data type of the specified value.
Data Types in Python
Python has several built-in data types, including:
- int: represents integer values, e.g., 5, -10, 100
- float: represents floating-point values with decimal places, e., 3.14, -0.5, 2e-3
- str: represents string values enclosed in single quotes (”) or double quotes (“”)
- bool: represents boolean values either True or False
- list: represents an ordered collection of items enclosed in square brackets ([])
- tuple: similar to lists but immutable (cannot be modified once created), enclosed in parentheses (())
- dict: represents key-value pairs enclosed in curly braces ({})
- set: represents an unordered collection of unique items enclosed in curly braces ({}) or created using the set() function.
None: represents the absence of a value or a null value.
Examples
Let’s see some examples of using the type() function to check the data type of different values:
Example 1:
x = 5
print(type(x))
This will output <class 'int'>
, indicating that the data type of x
is an integer.
Example 2:
y = 3.14
print(type(y))
This will output <class 'float'>
, indicating that the data type of y
is a float.
Example 3:
name = "John Doe"
print(type(name))
This will output <class 'str'>
, indicating that the data type of name
is a string.
Example 4:
is_valid = True