Like the while loop , the for loop provides a mechanism to repeat a task until a particular condition is True. The for loop is usually known as a determinate or definite loop because the programmer knows exactly how many times the loop will repeat. The number of times the loop has to be executed can be determined mathematically checking the logic of the loop.
The for….in statement is a looping statement used in python to iterate over a sequence of objects i.e. go through each item in a sequence. Here by sequence we mean just an ordered collection of items.
The syntax of a for loop is given below.
for loop_control_var in sequence: statement block
when a for loop is used, a range of sequence is specified (only once). The items of the sequence are assigned to the loop control variable one after the other. The for loop is executed for each item in the sequence. With every iteration of the loop, a check is made to identify whether the loop control variable has been assigned all the values in the range. If all the values has been assigned, the statement block of the loop is executed else the statements comprising the statement block of the for loop are skipped and the control jumps to the immediate statement following the for loop body.
Every iteration of the loop must make the loop control variable closer to the end of the range. So, with every iteration, the loop variable must be updated. Updating the loop variable makes it point to the next item in the sequence.
The range() function –
The range() is a built-in function in python that is used to iterate over a sequence of numbers.
The syntax of range() is
range(beg, end, [step])
The range() produces a sequence of numbers starting with beg (inclusive) and ending with one less than the number end. The step argument is optional (that is why it is placed in brackets). By default, every number in the range is incremented by 1 but we can specify a different increment using step. It can be both negative and positive but not zero.
Let’s write a program to print first n numbers using the range() in a for loop.
for i in range(1, 11): print(i, end=' ')
#output 1 2 3 4 5 6 7 8 9 10
We can also use the step parameter of the range function.
for i in range(2, 22, 2): print(i, end=' ')
#output 2 4 6 8 10 12 14 16 18 20
Key points to remember –
- if range function is given a single argument, it produces an object with values from 0 to argument – 1. For example range(10) is equal to writing range(0, 10).
- if range is called with two arguments, it produces values from the first to the second. For example range(0, 10)
- if range has three arguments, then the third argument specifies the interval of the sequence produced. In this case, the third argument must be an integer. For example range(2, 22, 2) .