Check with range() for Integers
In this step, you will learn how to use the range()
function in Python to generate a sequence of numbers and check if an integer falls within that range. The range()
function is particularly useful when you need to iterate over a sequence of numbers or create a list of integers within a specific interval.
Let's create a new Python script named range_check.py
in the ~/project
directory using the VS Code editor.
#!/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")
In this script:
- We define a variable
number
and assign it the value 25.
- We use the
range(1, 50)
function to generate a sequence of numbers from 1 up to (but not including) 50.
- We use the
in
operator to check if number
is present in the generated sequence.
- We use the
range(0, 101, 5)
function to generate a sequence of numbers from 0 up to (but not including) 101, with a step of 5 (i.e., 0, 5, 10, 15, ..., 100).
Now, let's run the script:
python ~/project/range_check.py
You should see the following output:
25 is within the range of 1 to 49
25 is within the range of 0 to 100 with a step of 5
Let's modify the script to change the value of number
to 7 and observe the output.
#!/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")
Run the script:
python ~/project/range_check.py
You should see the following output:
7 is within the range of 1 to 49
7 is outside the range of 0 to 100 with a step of 5
This demonstrates how to use the range()
function and the in
operator to check if an integer falls within a specific range in Python.