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.

  1. 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
  1. Run uv sync to install the dependency declared in the template’s pyproject.toml (colorama):
bash
1uv sync
  1. Navigate to the Ex5_Loops.py file that’s included in the repository that you cloned.
  2. Define a Python list named colors and assign it four foreground colors supported by the colorama python package.
  3. Define a function named saveFile.
  4. Call Python’s built-in open() function and pass colors.txt as the first argument and ‘a’ as the second. The ‘a’ mode means “append”.
  5. Define a for loop to iterate over each color in the Python list.
  6. 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.
  7. 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 Fore attribute. Since each color’s name (e.g. "red") matches a Fore attribute name (e.g. Fore.RED) when uppercased, you can look it up dynamically instead of writing a separate line for every color:
      python
      1print(getattr(Fore, color.upper()) + color)
  8. Finally, call the saveFile function to execute the program.
  9. 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).