Utilize the range() Function
In this step, you will learn how to utilize the range() function in Python. The range() function is a powerful tool for generating sequences of numbers, which are commonly used in loops and other programming constructs.
The range() function can be used in several ways:
range(stop): Generates a sequence of numbers from 0 up to (but not including) stop.
range(start, stop): Generates a sequence of numbers from start up to (but not including) stop.
range(start, stop, step): Generates a sequence of numbers from start up to (but not including) stop, incrementing by step.
Let's create a new Python script named range_function.py in your ~/project directory using the VS Code editor.
## ~/project/range_function.py
for i in range(5):
print(i)
In this script, we use the range(5) function to generate a sequence of numbers from 0 to 4. The for loop iterates through this sequence, printing each number.
Now, let's run the script using the following command in the terminal:
python ~/project/range_function.py
You should see the following output:
0
1
2
3
4
Next, let's modify the script to use the range(start, stop) form:
## ~/project/range_function.py
for i in range(2, 7):
print(i)
In this modified script, we use range(2, 7) to generate a sequence of numbers from 2 to 6.
Run the script again:
python ~/project/range_function.py
You should see the following output:
2
3
4
5
6
Finally, let's explore the range(start, stop, step) form:
## ~/project/range_function.py
for i in range(0, 10, 2):
print(i)
In this script, we use range(0, 10, 2) to generate a sequence of even numbers from 0 to 8.
Run the script:
python ~/project/range_function.py
You should see the following output:
0
2
4
6
8
By experimenting with different parameters, you can effectively use the range() function to generate various sequences of numbers for your Python programs.