python tutorial - for loop in python - learn python - python programming




 python for loop

Learn Python - Python tutorial - python for loop - Python examples - Python programs

  • A for-loop (or simply for loop) is a control flow statement for specifying iteration, which allows code to be executed repeatedly.
 for loop in python

Syntax:

           for <variable> in <sequence>:  

Explanation:

  • Initially, 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

Program to display table of Number:

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

Output:

2  
  
4  
  
6  
  
8  
  
10  
  • Program to find sum of Natural numbers from 1 to 10.
sum=0  
for n in range(1,11):  
    sum+=n  
print sum  

Output:

55 

Nested Loops

  • Loops defined within another Loop is called Nested Loop.
  • When an outer loop contains an inner loop in its body it is called Nested Looping.
 for loop python

Syntax:

for  <expression>:  
        for <expression>:  
            Body  
eg:

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.
  • Program to print Pyramid:
for i in range (1,6):  
    for j in range (5,i-1,-1):  
        print "*",  
    print  
  • Output:
>>>   
* * * * *  
* * * *  
* * *  
* *  
*  

Wikitechy tutorial site provides you all the learn python , online python programming course python programming class online , python coding for dummies , python programming classes online , online training python , online python training , python programming online course , python training classes

Related Searches to for loop in python