In python, for loop allows the loop to run over a specific sequence of values. In other words, for every value in the sequence, the loop runs once. Thus we can avoid infinite loops by using a for loop.
Syntax

Example
Similar to example of while loop lets handle same scenario with for loop:
for number in 1,2,3,4,5:
print("The current number is ",number)
Output
The current number is 1
The current number is 2
The current number is 3
The current number is 4
The current number is 5
In the above for loop , the statement inside the loop will execute for each value of number.
Another variation of for loop
In Python, there is an easy way to achieve this by using range(x,y,step). It creates a sequence from x to y-1 with a difference of step between each value.
Example
start=1
end=10
step=2
for number in range (start, end, step):
print("The current number is ", number)
Output
The current number is 1
The current number is 3
The current number is 5
The current number is 7
The current number is 9
In the above example of for loop, the start value will vary from 1 to end-1 i.e 9 and each step increase start value as step 2.
You must log in to post a comment.