Iteration Statements

Iteration Statements

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

  1. for loop
  2. 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.

Syntax

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)

Output

W
a 
y 
t 
o 
e
a
s
y
l
e
a
r
n

E.g 2

for x in range(5) :
    print("Waytoeasylearn")

Output

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.

Syntax

while condition : 
    body

Output

x = 1
while x <= 10: 
    print(x)
    x = x+1

Output

1
2
3
4
5
6
7
8
9
10
Infinite Loops
i=0;
while True : 
    i=i+1;
    print("Waytoeasylearn",i)
Nested Loops

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)

Output

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
Iteration Statements
Scroll to top