Wednesday 15 August 2018

The range() Function in Python

Lets use Range function of Python to write below code to print range of numbers between 0 to 4

------------------------------
for i in range(5):
    print(i)

------------------------------

The output of above code will be :

------------------------------

0
1
2
3
4
------------------------------

Now lets use Range function again of Python to see another scenario where 10 is not printed in the range of 5,10 but 5 is printed so it includes first number not the last
------------------------------

for i in range(5,10):
     print(i)

------------------------------

The output of above code is below

------------------------------
5
6
7
8
9

------------------------------

The given end point is never part of the generated sequence; range(10) generates 10 values, the legal indices for items of a sequence of length 10. It is possible to let the range start at another number, or to specify a different increment (even negative; sometimes this is called the ‘step’):

So lets take a scenario of below code :

---------------------------------

for i in range(0,10,3):
    print(i)
---------------------------------


The output of above code is 

------------------------------
0
3
6
9
------------------------------








No comments:

Post a Comment