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'.

for i in range(3): #i values are from 0 to 2 
   for j in range(4): #j values are from 0 to 3 
print('i=', i, '\t', 'j=',j) #display i and j values
							

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.

i= 0 		j= 0 
i= 0 		j= 1 
i= 0 		j= 2 
i= 0 		j= 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:

i= 1 	 	j= 0 
i= 1 	 	j= 1 
i= 1 	 	j= 2 
i= 1 	 	j= 3
i= 2 	 j= 0 
i= 2 	 j= 1 
i= 2 	 j= 2 
i= 2 	 j= 3


							

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()

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

for i in range(start, stop, step):

range function example with for loop

for i in range(1, 10, 2):
	print(i, end=', ')
for num in range(-2,5,1):
	print(num, end=", ")
for i in range(0, -10, -2):
    print(i)
for num in range(2,-5,-1):
	print(num, end=", ")
for number in range(4,-1,-1):
	print (number, end=', ')  #4, 3, 2, 1, 0
for i in range(8,5,-1):
  print(i)
for i in range(3,2,-1):
  print(i)