Nested Loops

 An inner loop within the repeating block of an outer loop is called Nested Loop.

The Inner Loop will be executed one time for each iteration of the Outer Loop.

Code

for i in range(2):
print("Outer: " + str(i))
for j in range(2):
print(" Inner: " + str(j))
PYTHON

Output

Outer: 0
Inner: 0
Inner: 1
Outer: 1
Inner: 0
Inner: 1

Nested Repeating Block

The one highlighted in the blue dotted line is the repeating block of the inner loop.

Code

for i in range(2):
print("Outer: " + str(i))
for j in range(2):
print(" Inner: " + str(j))
print("END")
PYTHON

In the above example, the below line is the repeating block of the nested loop.

Code

print(" Inner: " + str(j))
PYTHON

Output

Outer: 0
Inner: 0
Inner: 1
Outer: 1
Inner: 0
Inner: 1
END

Examples - Nested Loops

Example - 1: While loop inside a For loop

Example - 2: While loop inside a while loop

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form