Python range Function in for loop – this python tutorial will explain the purpose and use of Python range() function especially in for loop.
The Use of Python range Function in for loop
The range function
Normally, we use range() function in for loop statemt to execute a block of statements for a specified number of times.
The argument value we use in the range function decides how many times the loop will execute.
Why we use range function?
Actually the range function generates a list of numbers from zero to the value minus one. For instance, range(10)
produces ten values: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. The value minus one means, excluding the value itself. For example, the range(3) will give 0,1 and 2. It will exclude the number 3.
First and Last Value of range function
The range() function by default uses 0(zero) as the first value and value minus one as the last value produced. For example, range(5) will give total five values but from zero to 4. Here first value is by default zero and last value is the value minus one so 5-1 = 4.
The Syntax of range function in Python
- start is the first or starting number in the range. By default it is zero.
range(3) will give 0,1,2
range(1,3) will give 1,2,3
range(1,6) will give 1,2,3,4,5
so we will use start=1 and last=six, if we wish to produce a range of 1 to 5 numbers.
- last_minus_one represents the value before last. For example, if we use the range(5), it will produce 0, 1, 2, 3, 4. It will not give tha last value. It will generate total 5 values but from 0 to 4.
range(4) will give 0,1,2,3
range(1,5) will give 1,2,3,4
- The third argument is step. It represents the increment or decrement in starting value each time for producing the new number. It is an optional argument. By default its value is 1. Therefore if we ignore it, the step will be 1.
range(1,5,1) will give 1,2,3,4
range(1,7,2) will give 2,4,6 note the increment of 2
How to use range() function to display 10 down to 1
we use starting value as 10, last value as 0( zero) and step will be -1.
Hence range(10,0,-1) will produce 10,9,8,7,6,5,4,3,2,1. Zero will be excluded.
Write down a Python for statement with range function to show 10 down to 1 (first 10 numbers in reverse)
for i in range(10,0,-1): print(i)
will give the output: