Python Nested for Loop Statements

Loops defined within another Loop are called Nested Loops. Nested loops are used to iterate matrix elements or to perform complex computation.

  When an outer loop contains an inner loop in its body it is called Nested Looping.


Python Nested For Loop Syntax

for  < expression >:  
        for < expression >:  
            Body to execute 

for i in range(1,6):  
    for j in range (1,i+1):  
        print (j,end=""),  
    print()  
1
12
123
1234
12345

Using else Statement with Loops

Python supports to have an else statement associated with a loop statement loopâ??s else clause runs when no break occurs


# for loop with else block
for i in range(5):
	print(i)
else:
	print("Else block ...")
0
1
2
3
4
Else block ...

Example : using for with else and break


# for loop with else block with break
for i in range(5):
	print(i)
	if i==3:
		break
else:
	print("Else block ...")
0
1
2
3