# JythonTutorial:8 Loops

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Contents

# 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.

a = 0
while a < 5:
a = a + 1
print 'a=',a

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:

for i in [1,3,5,7]:
print i

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.

print  range(5,10)

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

L=range(0,5,2)
print L

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

for i in range(10):
print i

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

for i in range(10):
if (i==5): break
print i

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

for i in range(10):
if (i==5): continue
print i