The range function in Python is a general function that can be used in a variety of ways. It is used with for loops to generate indexes, but you can use this function anywhere you need integers in a particular series of steps. If you have never used the range function in Python, then this article is for you. In this article, I will take you through a tutorial on the range function in Python.
Range Function in Python
There are so many inbuilt functions in Python which makes it easy to learn programming language. One of those inbuilt functions is the range function. It is used to generate integers in a series of steps. The range function has three parameters (start, stop, step).
When using the range function, if you pass only one parameter, the default is the stop value, which will return a sequence of integers from 0 (default) to the number you entered as a stop parameter. For example, in the code below, I am using the range function with a single parameter as 10, which returns integers from 0 to 9:
for i in range(10): print(i)
0 1 2 3 4 5 6 7 8 9
Always remember that the value you will add as the stop parameter will be exclusive. If you will pass two parameters in the range function, then the first parameter is the starting value of the sequence and the second parameter is the last value of the sequence. It will generate a sequence of integers between your start and stop values. For example, just have a look at the code section below where my start parameter is 10, and stop parameter is 20:
for i in range(10, 20): print(i)
10 11 12 13 14 15 16 17 18 19
Always remember that the start value is inclusive, and the stop value is exclusive. If you pass three parameters in the range function, then this will complete all the arguments of the range function. Here, the first parameter will be the start value, the second parameter will be the stop value, and the third parameter will indicate how many steps you want in the series after each integer. For example, in the code below, I am using the range function to print a series of integers between 10 and 50 by incrementing 5 values after each integer:
for i in range(10, 50, 5): print(i)
10 15 20 25 30 35 40 45
So this is how you can use the inbuilt range function in Python.
In the range function in Python, the first parameter is the start value, the second parameter is the stop value, and the third parameter indicates how many steps you want in the series after each integer. I hope you liked this article on a tutorial on the range function in Python. Feel free to ask your valuable questions in the comments section below.