Usando type() para Identificar
Nesta etapa, você aprenderá como usar a função type() em Python para identificar o tipo de dado de uma variável. Compreender os tipos de dados é crucial para escrever código correto e eficiente.
A função type() retorna o tipo de um objeto. Vamos ver como ela funciona com diferentes tipos de dados.
-
Abra o editor VS Code no ambiente LabEx.
-
Crie um novo arquivo chamado type_example.py no diretório ~/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))
-
Execute o script usando o comando python no terminal:
python ~/project/type_example.py
Você deve ver a seguinte saída:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
<class 'list'>
<class 'tuple'>
<class 'set'>
<class 'dict'>
A saída mostra o tipo de dado de cada variável. Por exemplo, <class 'int'> indica que a variável é um inteiro, e <class 'str'> indica que a variável é uma string.
Compreender o tipo de dado de uma variável é importante porque determina quais operações você pode realizar nessa variável. Por exemplo, você pode realizar operações aritméticas em inteiros e floats, mas não em strings.
Vamos ver um exemplo de como a função type() pode ser usada para verificar se uma variável é de um tipo específico antes de realizar uma operação.
-
Adicione o seguinte código ao seu arquivo 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")
-
Execute o script novamente:
python ~/project/type_example.py
Você deve ver a seguinte saída:
15
Hello, World!
Neste exemplo, a função type() é usada para verificar se a variável num é um inteiro e a variável text é uma string antes de realizar as operações de adição e concatenação, respectivamente.