Python Nested loops

It is possible to write one loop inside another loop. For example, we can write a for loop inside a while loop or a for loop inside another for loop. Such loops are called 'nested loops'.


The indentation represents that the inner for loop is inside the outer for loop. Similarly, print() function is inside the inner for loop.

When outer for loop is executed once, the inner for loop is executed for 4 times. It means, when i value is 0, j values will change from 0 to 3.

Once the inner for loop execution is completed (j reached 3), then Python interpreter will go back to outer for loop to repeat the execution for second time. This time, i value will be 1. Again, the inner for loop is executed for 4 times. Hence the print() function will display the following output:


1) What would be the output of the following program

 for i in range(1, 11): #to display 10 rows

    for j in range(1, i+1): #no. of * = row number

 print('*', end='')

 print()

2) What would be the output of the following program

 for i in range(1, 6):

    for j in range(1, i+1):

 print(i, end='')

 print()


range Syntax

2) Examples