Nested Loops Revisited

As you saw in Section 5.4, Nested Loops, on page 90, loops can be nested inside other loops. Here is an example where we use nested loops to color every other line of an image black; the result of running this code is shown in Figure 7.2, on the next page:

Download loop/

import media lake = media.load_picture( 'lake.png')

width, height = media.get_width(lake), media.get_height(lake)

for y in range(0, height, 2): # Skip odd-numbered lines for x in range(0, width):

p = media.get_pixel(lake, x, y) media.set_color(p,

The nested loops result in a full set of iterations for the inner loop, for every iteration of the outer loop.

Was this article helpful?

0 0

Post a comment