Table of Contents > Programming in Jython > Loops
Loops

Loops are simply parts of a program that run over and over and over again. You will use loops when you want to tell the computer to perform the same action repeatedly but you don't want to write the same code repeatedly.

For

A "for" loop is one of the most common loops in programming; however, if you've done programming in langauges like C or Java, it is important to realize that "for" is used in Jython a little differently than in many other languages. A "for" loop in Jython tells the computer to do something for each element in a sequence.

In media computation, "for" loops are often used to change every sample in a sound file, or every pixel in a picture file, or every frame in a video file. You can make powerful for loops by combining them with the range function.

For example, if you wanted the computer to divide each number between 5 and 10 (not including 5 or 10), and print the results, you could use a "for" loop with the range function:

>>> for x in range(6,10):
...   print x/2.0
3.0
3.5
4.0
4.5

So we told the computer that for each number in the range six through 10, for x in range(6,10), divide it by 2.0 and print the result: print x/2.0

Notice that the body of the "for" statement--the part where we told it what to do print x/2.0--is indented.

jump to top