Verificar con range() para Enteros
En este paso, aprenderás cómo utilizar la función range()
en Python para generar una secuencia de números y verificar si un entero está dentro de ese rango. La función range()
es especialmente útil cuando necesitas iterar sobre una secuencia de números o crear una lista de enteros dentro de un intervalo específico.
Creemos un nuevo script de Python llamado range_check.py
en el directorio ~/project
utilizando el 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")
En este script:
- Definimos una variable
number
y le asignamos el valor 25.
- Utilizamos la función
range(1, 50)
para generar una secuencia de números desde 1 hasta (pero sin incluir) 50.
- Utilizamos el operador
in
para verificar si number
está presente en la secuencia generada.
- Utilizamos la función
range(0, 101, 5)
para generar una secuencia de números desde 0 hasta (pero sin incluir) 101, con un paso de 5 (es decir, 0, 5, 10, 15, ..., 100).
Ahora, ejecutemos el script:
python ~/project/range_check.py
Deberías ver la siguiente salida:
25 is within the range of 1 to 49
25 is within the range of 0 to 100 with a step of 5
Modifiquemos el script para cambiar el valor de number
a 7 y observemos la salida.
#!/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")
Ejecuta el script:
python ~/project/range_check.py
Deberías ver la siguiente salida:
7 is within the range of 1 to 49
7 is outside the range of 0 to 100 with a step of 5
Esto demuestra cómo utilizar la función range()
y el operador in
para verificar si un entero está dentro de un rango específico en Python.