Ex5 - Looping through a List:
Objective: Loop through a list of colors using a function call to print the list of colors to a text file.
Description: Think of your four favorite colors. Store these colors in a Python list, and then use a for loop to print the name of each color to a text file.
- Note: To complete this exercise, please follow the instructions on the Getting Started > Tools > git and Getting Started > Tools > uv pages to clone the exercise template and set up your environment with uv.
- Clone the exercise template repository:
bash
1git clone https://github.com/willkapakos/Ex5.git- Then, move into the folder that was created:
bash
1cd Ex5- Run uv sync to install the dependency declared in the template’s
pyproject.toml(colorama):
bash
1uv sync- Navigate to the Ex5_Loops.py file that’s included in the repository that you cloned.
- Define a Python list named
colorsand assign it four foreground colors supported by the colorama python package. - Define a function named
saveFile. - Call Python’s built-in open() function and pass
colors.txtas the first argument and ‘a’ as the second. The ‘a’ mode means “append”. - Define a for loop to iterate over each color in the Python list.
- Inside the for loop, call the write() method to write each color to the text file. Be sure to include a newline character (\n) at the end of each color so that each color is written on a new line in the text file.
- Also inside the for loop, use the colorama package (installed via
uv sync) to print each color’s name to the terminal in that actual color.- At the top of your file, import and initialize colorama:
python
1from colorama import Fore - Then, for each color, print its name using the matching
Foreattribute. Since each color’s name (e.g."red") matches aForeattribute name (e.g.Fore.RED) when uppercased, you can look it up dynamically instead of writing a separate line for every color:python1print(getattr(Fore, color.upper()) + color)
- At the top of your file, import and initialize colorama:
- Finally, call the
saveFilefunction to execute the program. - Run your script using uv run Ex5_Loops.py.
The output in the colors.txt text file should look like this depending on the colors you choose:
1red
2green
3blue
4yellow- In the terminal, you should see each color name printed in its matching color (e.g., “red” printed in red text, “green” printed in green text, and so on).