Python tutorial- for loop

Python Loops

Loops are statements that can execute a block of code again and again while the condition is true.

For Loop

You can use for statement to generate a loop with a specific need. For example, you might want to use for loop to execute a block of code for each item of a list. > >>lst1=[1,2,3,4,5]
>>> for i in lst1:
            print i,
1 2 3 4 5
For example, let’s write a program to generate a multiplication table as shown below: 1*1=1          2*1=2                   3*1=3         ……  9*1=1 1+2=2         2*2=4                   3*2=6          ……  9*2=18 …….           …….                   …….           ……  …….

1*9=9         2*8=18                 3*9=27         ……  9*9=81
for i in lst1:
        for j in lst2:
                print  j,'*',i,'=',i*j,'  ',
        print '\n'
Note: we use range() method to generate a list of  range values. If you want to generate a list of 9 integer numbers from 1 to 9, you will write range(1,10). If you want to generate a list in which every its element increases by a fixed number other than 1, you can specify the loop step number (third argument) in the range method. The Python code below displays a list of odd numbers

from 1 to 10:
>>>for i in range(1,10,2) # step=2
              print "%d" %i


This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.