In Python range() function generates sequence of numbers which we can be iterated using for loop. Let’s look an example as below.
Example.
for val in range(4):
print(val)
In the above loop, range(4) will generate numbers from 0 to 4 i.e; 0,1,2,3,4
There are 3 ways to define a range
- range(stop) #from 0 to stop-1, incrementing by 1
- range(start,stop) #from start to stop-1, incrementing by 1
- range(start,stop,step) #from start to stop-1, incrementing by step
Let’s see some examples of range() and it’s output as below.
range(5) => 0,1,2,3,4
range(5,10) =>5,6,7,8,9
range(5,12,2) =>5,7,9,11
Let’s write a program using range() as below
Program : Print cubes of numbers from range 2 to 10.
#print cubes of numbers from 2 to 10
for i in range(2,10):
print("cube of",i,"is ",i**3)
In this above program we have taken 2 arguments in range() as start =2 and stop =10. We are using for loop to loop the numbers from 2 to 9 and will print it’s cube. You can see the Output in below snap.
Output
I hope you will like this post. Happy Blogging!