Learn Python Programming

Nested Loops


Nested loops are one loop inside the 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.

Syntax

for [first iterating variable] in [outer loop]: # Outer loop
                ...
                statements
                ...
    for [second iterating variable] in [nested loop]:   # Nested loop
                     ...
                     statements
                     ...

Example Nested Loops in Python:

#to display stars in right angles triangular form
for i in range(1,11):
		for j in range(1,i+1):
				print('*', end='')
		print()

#Output:
*
**        
***       
****      
*****     
******    
*******   
********  
********* 
**********