Looping

Lopping means repeating something or some kind of work again and again, If we have to print hello user once,twice or thrice, it sounds easy task but if someones says to print it thousands time or more,then it is not a good practice to write code again and again. Therefore loops comes to rescue the programmer and help them repeat the same line of code again and again as much time they want.

we start learning loops from the first loop i.e. the for loop

For Loop

Python for loop is used to iterate the elements of a collection in the order that they appear. This collection can be a sequence(list or string).

Python For Loop Syntax

  • for <variable> in <sequence>:  

 

Output:

  • 1  
  • 7  
  • 9  

 

Explanation:

  • Firstly, the first value will be assigned in the variable.
  • Secondly all the statements in the body of the loop are executed with the same value.
  • Thirdly, once step second is completed then variable is assigned the next value in the sequence and step second is repeated.
  • Finally, it continues till all the values in the sequence are assigned in the variable and processed.

Python For Loop Simple Example

  • num=2  
  • for a in range (1,6):  
  •     print  num * a  

 

Output:

  • 2  
  •   
  • 4  
  •   
  • 6  
  •   
  • 8  
  •   
  • 10  

 

Python Example to Find Sum of 10 Numbers

 
  • sum=0  
  • for n in range(1,11):  
  •     sum+=n  
  • print sum  

Output:

  • 55  

 

Python Nested For Loops

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  

 

Python Nested For Loop Example

  • for i in range(1,6):  
  •     for j in range (1,i+1):  
  •         print i,  
  •     print  

Output:

  • 1  
  • 2 2  
  • 3 3 3  
  • 4 4 4 4  
  • 5 5 5 5 5  

 

Explanation:

For each value of Outer loop the whole inner loop is executed.

For each value of inner loop the Body is executed each time.

 

Python Nested Loop Example 2

  • for i in range (1,6):  
  •     for j in range (5,i-1,-1):  
  •         print “*”,  
  •     print  

 

Output: 

  • * * * * *  
  • * * * *  
  • * * *  
  • * *  
  • *