Python 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]:


1

Firstly, the first value will be assigned in the variable.

2

Secondly all the statements in the body of the loop are executed with the same value.

3

Thirdly, once step second is completed then variable is assigned the next value in the sequence and step second is repeated.

4

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 of above example  :


    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 of above example  :


    55

Python Nested For Loops

Example of Nested for loop :



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

output of above example  :


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



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

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


lets see one more example of patter program :



for i in range (1,6):
    for j in range (5,i-1,-1):
       print "*",
    print

output of above example  :


    * * * * *
    * * * *
    * * *
    * *
    *

advertisement