How to Use range
in Python
In Python, the range
function generates a sequence of numbers within a specified range. It is commonly used in looping constructs such as for
loops. This tutorial will explain how to use the range
function effectively in your Python code.
Syntax
The syntax of the range
function is as follows:
python
range(start, stop, step)
start
: Optional. Specifies the starting value of the sequence (inclusive). If not specified, it defaults to 0.stop
: Required. Specifies the ending value of the sequence (exclusive).step
: Optional. Specifies the difference between each number in the sequence. If not specified, it defaults to 1.
Examples
Example 1: Iterating Over a Range of Numbers
The most common use of the range
function is to iterate over a sequence of numbers. Here’s an example:
python
for i in range(5):
print(i)
Output:
0
1
2
3
4
Example 2: Specifying Start and Stop Values
You can specify the starting and ending values for the range
function. Here’s an example that generates numbers from 1 to 5:
python
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
Example 3: Using a Step Value
You can also specify a step value to generate numbers with a specific interval. Here’s an example that generates even numbers between 0 and 10:
python
for i in range(0, 11, 2):
print(i)
Output:
0
2
4
6
8
10
Conclusion
The range
function is a powerful tool in Python for generating a sequence of numbers. By understanding and utilizing its syntax, you can effectively utilize it in your Python code for various purposes.