BeginnersTutorial:Tutorial/Lesson 6

From jWork.ORG
Jump to: navigation, search

Lesson 6: Loops

The statements in the for loop repeat continuously for a specific number of times. It us up to you to decide how many times a statement should be repeated.

The "while" loop

One other point is that the code can 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 5, do the following: Make 'a' larger than what it already is, and then print on-screen what 'a' is now worth. This is repeated until "a" equals 5.

The "for" loop

The loop based on "for" is also very popular. It is used to repeat a statement repeatedly. Let's look at 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. In this example, this loop prints the numbers:

1
3
5
7



Often we need to do something a large number of times, in which case typing a long list become boring. In this case we can use the statement range() It takes at least 2 numbers: first the number at which the list 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's print values from 0 to 10 in a 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 repetition, without exiting the loop:

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