Python Programming

Nested For Loop In Python

In Programming, Python by Baqir Ali

A loop within another loop is called a nested loop. A real-life nested loop is like the hour is the outer loop which has a minute and second as the inner loop. For each hour minute runs 60 times and for each minute second run 60 times. It means for each outer loop the inner loop should run completely.

Implementing a pseudo code for hour, minute, second

for h in range(1,12):
    for m in range(0,59):
        for s in range(0,59):
            statement to be execute

Nested loop examples in Python

Example 1:

for row in range(1,5):
    print(row,' - ', end='')
    for col in range(1,5):
        print(col,end=' ')
    print()

output:

1 – 1 2 3 4
2 – 1 2 3 4
3 – 1 2 3 4
4 – 1 2 3 4

In the above example at the start of the line value of the row is printed and after that the inner loop starts which run from 1-5, whenever the inner loop completes its iteration then it jumps back to the outer loop. This process continues until the outer loop is false. The last print() statement prints ‘\n’ which is a new line.

Printing Diamonds with stars in Python

Example 2:

for row in range(5):
    for col in range(5):
        print("X",end=' ')
    print()

Output:

X X X X X
X X X X X
X X X X X
X X X X X
X X X X X

Example 3:

for row in range(5):
    for col in range(0,row+1):
        print("X",end=' ')
    print()

Output:

X
X X
X X X
X X X X
X X X X X

Example 4:

for row in range(5):
    for col in range(row,5):
        print("X",end=' ')
    print()

Output:

X X X X X
X X X X
X X X
X X
X

Example 5:

for row in range(5):
    for space in range(row,5):
        print(' ',end='')
    for col in range(0,row+1):
        print("X",end=' ')
    print()

Output:

     X 
    X X 
   X X X 
  X X X X 
 X X X X X 

Support us by sharing this post