Verificar com range() para Inteiros
Nesta etapa, você aprenderá como usar a função range() em Python para gerar uma sequência de números e verificar se um inteiro está dentro desse intervalo. A função range() é particularmente útil quando você precisa iterar sobre uma sequência de números ou criar uma lista de inteiros dentro de um intervalo específico.
Vamos criar um novo script Python chamado range_check.py no diretório ~/project usando o editor VS Code.
#!/usr/bin/env python3
## Define a variable
number = 25
## Check if the number is within the range of 1 to 50 (exclusive)
if number in range(1, 50):
print(f"{number} is within the range of 1 to 49")
else:
print(f"{number} is outside the range of 1 to 49")
## Check if the number is within the range of 0 to 100 with a step of 5
if number in range(0, 101, 5):
print(f"{number} is within the range of 0 to 100 with a step of 5")
else:
print(f"{number} is outside the range of 0 to 100 with a step of 5")
Neste script:
- Definimos uma variável
number e atribuímos a ela o valor 25.
- Usamos a função
range(1, 50) para gerar uma sequência de números de 1 até (mas não incluindo) 50.
- Usamos o operador
in para verificar se number está presente na sequência gerada.
- Usamos a função
range(0, 101, 5) para gerar uma sequência de números de 0 até (mas não incluindo) 101, com um passo de 5 (ou seja, 0, 5, 10, 15, ..., 100).
Agora, vamos executar o script:
python ~/project/range_check.py
Você deve ver a seguinte saída:
25 is within the range of 1 to 49
25 is within the range of 0 to 100 with a step of 5
Vamos modificar o script para alterar o valor de number para 7 e observar a saída.
#!/usr/bin/env python3
## Define a variable
number = 7
## Check if the number is within the range of 1 to 50 (exclusive)
if number in range(1, 50):
print(f"{number} is within the range of 1 to 49")
else:
print(f"{number} is outside the range of 1 to 49")
## Check if the number is within the range of 0 to 100 with a step of 5
if number in range(0, 101, 5):
print(f"{number} is within the range of 0 to 100 with a step of 5")
else:
print(f"{number} is outside the range of 0 to 100 with a step of 5")
Execute o script:
python ~/project/range_check.py
Você deve ver a seguinte saída:
7 is within the range of 1 to 49
7 is outside the range of 0 to 100 with a step of 5
Isso demonstra como usar a função range() e o operador in para verificar se um inteiro está dentro de um intervalo específico em Python.