Usar type() para identificar
En este paso, aprenderás cómo usar la función type()
en Python para identificar el tipo de datos de una variable. Comprender los tipos de datos es crucial para escribir código correcto y eficiente.
La función type()
devuelve el tipo de un objeto. Veamos cómo funciona con diferentes tipos de datos.
-
Abre el editor de VS Code en el entorno de LabEx.
-
Crea un nuevo archivo llamado type_example.py
en el directorio ~/project
.
## 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))
-
Ejecuta el script utilizando el comando python
en la terminal:
python ~/project/type_example.py
Deberías ver la siguiente salida:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
<class 'list'>
<class 'tuple'>
<class 'set'>
<class 'dict'>
La salida muestra el tipo de datos de cada variable. Por ejemplo, <class 'int'>
indica que la variable es un entero, y <class 'str'>
indica que la variable es una cadena de texto.
Comprender el tipo de datos de una variable es importante porque determina qué operaciones se pueden realizar en esa variable. Por ejemplo, se pueden realizar operaciones aritméticas en enteros y números de punto flotante, pero no en cadenas de texto.
Veamos un ejemplo de cómo se puede usar la función type()
para verificar si una variable es de un tipo específico antes de realizar una operación.
-
Agrega el siguiente código a tu archivo type_example.py
:
## 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")
-
Ejecuta el script nuevamente:
python ~/project/type_example.py
Deberías ver la siguiente salida:
15
Hello, World!
En este ejemplo, la función type()
se utiliza para verificar si la variable num
es un entero y la variable text
es una cadena de texto antes de realizar las operaciones de suma y concatenación, respectivamente.