Python - range Function
In Python, the range()
method returns an immutable sequence of numbers. It can be used to control the repetition of a block in the for loop.
range([start], stop, [step])
All three parameters should be integers. The sequence starts with 0, by default, unless the [start] parameter is provided. The only mandatory parameter for the above function is stop. The last number in the sequence is the number before stop. The numbers in between are incremented with the [step] value, which is 1 by default.
range(5) will generate 0,1,2,3,4
range(1,10) will generate 1,2,3,4,5,6,7,8,9
range(10,21,2) will generate 10,12,14,16,18,20
We can run the for loop over a range to print each number in a given range.
x=range(5)
for num in x:
print(num)
1
2
3
4
The range()
function can also be used directly with the for loop.
for num in range(5):
print(num)
The following code computes the factorial value of a number taken as input. The factorial value of a certain number is the product of all numbers between 1 and the number itself. We use the range()
function to obtain the sequence. The body of the for loop performs cumulative multiplication of all numbers in the range.
num=int(input("Enter a number: "))
fact=1
for x in range(1, num+1):
fact=fact*x
print ("Factorial of {} is {}".format(num,fact))
Factorial of 4 is 24