Range in Python

Python range() function

The Python range() function is used to display the number from the given range. The range() function takes three arguments as parameters.

Python range() function Syntax

range(startValue, endValue, stepValue) 

Purpose of startValue :

The startValue is the number from which the range should begin. It is optional, and if we don’t specify the startValue, then it uses a default value i.e 0.

Purpose of endValue :

The endValue is the limit of the range() function. It is the number from which the range should end. We can’t omit the end value. If we set the end value to 5, we will see a number until we reach 4.

Purpose of stepValue :

The stepValue specifies the increment or decrement in a number. It is also optional. If we don’t specify the step value then it will consider 1 (that means increment by 1). stepValue can be positive or negative.

Note: range() function is used with a for loop.

Now let’s understand the range function with the help of examples :

Example 1:

for i in range(1,10,1):
    print(i,end=" ")


Output :

1 2 3 4 5 6 7 8 9 

Note that startValue is always included but endValue is always excluded.

Example 2:

for i in range(1,10,3):
    print(i,end=" ")


Output :

1 4 7

As we read above start and step value is optional. Now see the examples where we omit the start and stepValue.

Example 3:

for i in range(10): #single argument is consider as a end value
    print(i,end=" ")


Output :

0 1 2 3 4 5 6 7 8 9 

In the above output 0 prints, when we omit the start value it will take 0 by default. The increment by 1 because when we omit the step value it will increment by 1.

Example 4:

for i in range(2,10): # two argument is consider as a start and end value
    print(i,end=" ")


Output :

2 3 4 5 6 7 8 9 

Here, we omit one argument. This omitted argument is considered a stepValue. Therefore it increments by 1 in the output.

Note that if we omit two arguments then it will omit the start and stepValue and if we omit one argument then it will omit stepValue.

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Python Online Quiz

Level up your coding skills with our interactive programming quiz!