16.Nested Loops

A nested loop is a loop inside another loop.The "inner loop" will be executed completely for each iteration of the "outer loop":
we can nest while loops, for loops or the combination.

Syntax
The syntax for a nested while loop statement in Python programming language is as follows 
 
while expression: 
     while expression: 
         statement(s) 
     statement(s)
 
The syntax for a nested for loop statement in Python programming language is as follows 
for iterating_var in sequence:
     for iterating_var in sequence: 
         statements(s) 
     statements(s) 
Note: indentation is very important to identify the code blocks
Example:
i=1
while i<=3:
   j=1
   while j<=i:
      print(j,end=' ')            # inner while loop
      j=j+1
   print()
   i=i+1
here the inner while loop will execute 'i '  times and  'i'  will very from 1 to 3 in the outer loop.So it will print
1
1 2
1 2 3

In the same way for loop can also be nested.The above program can be written using nested for loop as follows

for i in range(1,4):
    for j in range(1,i+1):
        print (j,end=' ')
    print()

Note: Nested loops are widely used for processing lists, matrix, sorting etc..

Comments

Popular posts from this blog

Python For Machine Learning - CST 283 - KTU Minor Notes- Dr Binu V P

46.Classes and Objects in Python- Accessors and mutators

KTU Python for machine learning Sample Question Paper and Answer Key Dec 2020