Use type() to Identify
In this step, you will learn how to use the type()
function in Python to identify the data type of a variable. Understanding data types is crucial for writing correct and efficient code.
The type()
function returns the type of an object. Let's see how it works with different data types.
-
Open the VS Code editor in the LabEx environment.
-
Create a new file named type_example.py
in the ~/project
directory.
## Check the type of an integer
x = 10
print(type(x))
## Check the type of a float
y = 3.14
print(type(y))
## Check the type of a string
z = "Hello"
print(type(z))
## Check the type of a boolean
a = True
print(type(a))
## Check the type of a list
b = [1, 2, 3]
print(type(b))
## Check the type of a tuple
c = (1, 2, 3)
print(type(c))
## Check the type of a set
d = {1, 2, 3}
print(type(d))
## Check the type of a dictionary
e = {"name": "Alice", "age": 30}
print(type(e))
-
Run the script using the python
command in the terminal:
python ~/project/type_example.py
You should see the following output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
<class 'list'>
<class 'tuple'>
<class 'set'>
<class 'dict'>
The output shows the data type of each variable. For example, <class 'int'>
indicates that the variable is an integer, and <class 'str'>
indicates that the variable is a string.
Understanding the data type of a variable is important because it determines what operations you can perform on that variable. For example, you can perform arithmetic operations on integers and floats, but not on strings.
Let's see an example of how the type()
function can be used to check if a variable is of a specific type before performing an operation.
-
Add the following code to your type_example.py
file:
## Check if a variable is an integer before adding 5 to it
num = 10
if type(num) == int:
result = num + 5
print(result)
else:
print("Variable is not an integer")
## Check if a variable is a string before concatenating it with another string
text = "Hello"
if type(text) == str:
greeting = text + ", World!"
print(greeting)
else:
print("Variable is not a string")
-
Run the script again:
python ~/project/type_example.py
You should see the following output:
15
Hello, World!
In this example, the type()
function is used to check if the variable num
is an integer and the variable text
is a string before performing the addition and concatenation operations, respectively.