Chapter 8.6 - Python Loops & Lists

8.6. Python Loops and Lists

8.6.1. Python Loops

Loops are used to repeat a block of code. In Python, the : is used after for and while loops. The for uses a counter variable, often i for index that is incremented every time in the loop within a range of values including the initial value in the range and up to but not including the last value in the range. The statements under the loop must all be indented and lined up under the for.

The following code will print out the numbers 1 to 10. Try it out by clicking the “Run” button. Click on the CodeLens button and then next to step through the code line by line and see the i variable change.

8.6.2. Python Lists

Lists in Python are indicated with square brackets: [].

Lists in Python are numbered starting from 0. The list name can be followed by the square brackets with an index number in it to retrieve the element at that index. For example animals[0] will return the first element in the list. Change the index variable below to see what is printed out.

Loops are often used to go through a list of items. In fact, the range function we used in the for loops above actually creates a list of numbers. Instead of range, we can simply use the list name in a for loop to visit each item in the list.

The following code will print out each item in the list on a separate line.

8.6.3. Picture Project

Images in photographs are made up of pixels which are tiny picture elements that color in the image. The color of a pixel is represented using the RGB (Red, Green, Blue) color model, which stores values for red, green, and blue, each ranging from 0 to 255. You can make any color by mixing these values!

Try the following Color Chooser by moving the sliders to see the RGB values for each color. What is the RGB value for black? What is the RGB value for white? What is the RGB value for purple?

The following code will create a picture from a file and then loop through all the pixels in the picture. It will then change the color of any pixel that is close to white to cyan. This code and project are based on the Picture Lab by Dr. Barbara Ericson.

Run the following code to see how it changes the white background of the image to purple/violet with high red and blue values. The original image is above. Can you write an if statement to change the color of the student’s hair which is close to black? Can you change the red t-shirt to another color? You can also experiment with the files kitten.jpg and puppies.jpg.

Last updated