Tutorial:Jython/8 Loops

From HandWiki

Loops

The "while" loop

One other point is that the code to be executed if the conditions are met. That means that if you want to loop the next five lines with a 'while' loop, you must put a set number of spaces at the beginning of each of the next five lines. Python requires that you do it.

<jc lang="python"> a = 0 while a < 5:

 a = a + 1
 print 'a=',a

</jc>

This example does this: as long as 'a' is less than 10, do the following: Make 'a' one larger than what it already is, and then print on-screen what 'a' is now worth.

The "for" loop

The loop based on "for" is also very popular. It is used to repeat a statement repeatedly. Let as consider this example:

<jc lang="python"> for i in [1,3,5,7]:

 print i

</jc> What it does is this: For each thing in the list that follows, execute some statement.

Often we need to do something a large number of times, in which case typing a long list become tedious. In this case use the statement range() It takes at least 2 parameters: first the number at which the list it returns should start, and second, the number up to which the list should go.

<jc lang="python"> print range(5,10) </jc>

range() takes an optimal third parameter that specifies the step between each number in the list:

<jc lang="python"> L=range(0,5,2) print L </jc>

Let us print values from 0 to 10 in a for loop:

<jc lang="python"> for i in range(10):

 print i

</jc>

One can also break this loop if a condition is met:

<jc lang="python"> for i in range(10):

 if (i==5): break 
 print i

</jc>

You can also use the continue statement if you want to skip some iteration, without exiting the loop:

<jc lang="python"> for i in range(10):

 if (i==5): continue 
 print i

</jc>