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 

    Example)
    drag_handle
     for i in range(1,6):  
        for j in range (1,i+1):  
            print (j,end=""),  
        print()  
    Output:
    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

    Example)
    drag_handle
     
    # for loop with else block
    for i in range(5):
    	print(i)
    else:
    	print("Else block ...")
    Output:
    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 ...")

    Output:
    0
    1
    2
    3
    

What next?

The next topic is Python while Loop Statements

Share this page