< Back

Lab 12: Images


Practice Problem 1

Write a function list_letters(a_phrase), which takes a string as a parameter. Your function should list all of the characters out of a_phrase, each on their own line.

Example

>>> list_letters("INQ 241A")
I
N
Q

2
4
1
A
>>> list_letters("Trexler")
T
r
e
x
l
e
r

Hint

A function always begins with the def keyword. You then provide some name for the function (list_letters in this case). Finally, you define any parameters you want between the parenthesis (a_phrase in this activity). Remember, this just defines a variable you can use within the function, and can be called anything you want. Follow the naming convention here, though. Don't forget the : at the end.

All lines that belong to the function must be indented one tab from the left margin. This signifies that you are including that line of code with the function.

You can use a for loop to go through each character of the string individually. Recall that a for loop on strings is of the form for a_variable in some_string:


Practice Problem 2

Write a function list_integers(start, end), which takes two integers as parameters. This function should print all of the values that exist in the range specified.

Example

>>> list_integers(0, 10)
0
1
2
3
4
5
6
7
8
9
>>> list_integers(5, 10)
5
6
7
8
9
>>> list_integers(5, 15)
5
6
7
8
9
10
11
12
13
14

Hint

This activities is also going to use a for loop. In this case, you don't have a string you are executing on. However, you do know the range of integers you want to iterate over.

The range function takes several parameters. However, the one you want to use here is range(beginning, end), which takes the value you wish to start generating integers, and the last value you wish to generate. This is the second value you specify for your for loop.


Lines

In a file called hair_color.py, write a function called change_hair_to_red(picture, hair_color). This function should takes two parameters: the picture you are going to modify, and the color of hair you wish to make red. This function should change any pixel that has a color "similar" to hair_color to straight red. Consider two colors "similar" if their "distance" is less than 50.

Example

Before After

Hint

Like previously, you want to iterate over all of the pixels of your image. To do this, you need to use a for loop over the pixels of the image. You can get a listing of the pixels using the getPixels(a_picture) function.

getColor(a_pixel) will give you the color of a pixel from the image.

You can use the distance function to determine if two pixels have a color that is similar. If a pixel's color is stored in a variable called pixel_color, distance(hair_color, pixel_color) will return a floating point value representing how far apart the colors are.

The setColor(pixel, color_value) function can be used to set a specific pixel to a specific color.