For Loop: 3 Important Things To Know About It

For Loop is without a doubt the best looping statement to iterate through a sequence of ordered data, here you will read about the 3 important things which make the for-loop more powerful in execution.

What Is A For Loop?

for loop is used for iterating over a sequence of statements for each item in a list, tuple, set, etc.

Example Program:

for friend in ["Joe", "Robin", "Rajan", "Balaji", "Paris"]:
invite = "Hi " + friend + ". Please come to my party!"
print(invite)

Output:

Hi Joe. Please come to my party!
Hi Robin. Please come to my party!
Hi Rajan. Please come to my party!
Hi Balaji. Please come to my party!
Hi Paris. Please come to my party!




 

Explanation:

The variable friend in the for statement at line 1 is called the loop variable.  





We could have chosen any other variable name instead, such as tomato:
the computer or the compiler just doesn’t care. Lines 2 and 3 are the
loop body.





The loop’s body is always indented.  





The indentation determines precisely what statements are “in the body of the loop”. 





On each iteration or pass of the loop, first, a check is done to see if there are still more items to be processed.  





If there are none left (this is called the terminating condition of the loop), the loop has finished.





Program execution continues at the following statement after the loop body, (e.g. in this case the following statement below the comment in line 4)





If there are items still to be processed, the loop variable is updated to refer to the next item in the list.





This means, in this case, that the loop’s body is executed here 7 times, and each time friend will refer to a different friend.





At the end of each execution of the body of the for loop, Python
returns to the for statement, to see if there are more items to be
handled, and to assign the next one to a friend.





Range() Function:





To loop through a set of code a specified number of times, you can use the range() function, The range()
function returns a sequence of numbers, starting from 0 by
default, increments by 1 (by default), and ends at a specified number.


Example:

for x in range(10):
print(x)

Output:

0
1
2
3
4
5
6
7
8
9



Break Statement In For Loop:

The break statement is used to stop the loop before it has looped through all the items.

Example: 

#Exit the loop when x is "Cherry"
fruits = ["Grapes", "Apple", "Cherry"]
for x in fruits:
print(x)
if x == "Cherry":
break

Output:

Grapes

Apple


 

Continue Statement In For Loop:

The continue statement is used to stop the current iteration of the loop and continue with the next value.





Example:

#Do not print Banana
fruits = ["Apple", "Banana", "Cherry"]
for x in fruits:
if x == "banana":
continue
print(x)

Output:

Apple

Cherry