Iteration is the process where a set of instructions or statements is executed repeatedly for a specified number of time or until a condition is met. Such a statement is known as iterative statement or iteration statements.
If we want to execute a group of statements multiple times then we should go for Iterative statements. Python supports 2 types of iterative statements
- for loop
- while loop
1. for loop
If we want to execute some action for every element present in some sequence (it may be string or collection) then we should go for for loop.
for x in sequence: Body
Where sequence can be string or any collection and Body will be executed for every element present in the sequence.
s="Waytoeasylearn" for x in s : print(x)
W a y t o e a s y l e a r n
for x in range(5) : print("Waytoeasylearn")
Waytoeasylearn Waytoeasylearn Waytoeasylearn Waytoeasylearn Waytoeasylearn
2. while loop
If we want to execute a group of statements iteratively until some condition false, then we should go for while loop.
while condition : body
x = 1 while x <= 10: print(x) x = x+1
1 2 3 4 5 6 7 8 9 10
i=0; while True : i=i+1; print("Waytoeasylearn",i)
Sometimes we can take a loop inside another loop,which are also known as nested loops.
for i in range(4): for j in range(4): print("i=",i," j=",j)
i= 0 j= 0 i= 0 j= 1 i= 0 j= 2 i= 0 j= 3 i= 1 j= 0 i= 1 j= 1 i= 1 j= 2 i= 1 j= 3 i= 2 j= 0 i= 2 j= 1 i= 2 j= 2 i= 2 j= 3 i= 3 j= 0 i= 3 j= 1 i= 3 j= 2 i= 3 j= 3