Adding Colour To Python Code

On a recent project I was required to build a small program using Python only. I really enjoyed getting to focus on logic and solving problems, but I did miss the frontend design. In my program I needed to give feedback to the user when their text input was submitted and validated. Printing a message to the terminal was sufficient but I wondered whether I could take it further. Through a quick Google, I came across Colorama.

What is Colorama?

Colorama is a built-in Python module which displays text in different styles and colours. It offers three formatting options of: Back, Fore and Style, which can change the colour of the text itself, the background of the text and the thickness of the text.

Colorama options - credit - github: tartley

Colorama gives an option of 8 colours - Black, Red, Green, Blue, Yellow, Magenta, Cyan and White. For providing user feedback, highlighting information or just brightening the code output up, these colours get the jobs done.

How do I use it?

In your command terminal, install Colorama using:

- pip3 install colorama for Python 3

- pip install colorama for older versions of Python

To ensure that Colorama allows a reset after each line of use it is important to set it's autoreset to True with this code:

- colorama.init(autoreset=True)

Colorama should be ready to go! I did import the library to the top of my Python file by adding:

- import colorama from colorama import Fore, Back, Style

This allowed me to access the commands within my Python file by adding my requests after the opening bracket of my print() or input() statements.

To colour text only my code was as follows:

- print(Fore.GREEN + "Inventory updated successfully")

Green Python text

- print(Fore.RED + "Input is not valid")

Red Python text

- print(Fore.YELLOW + "ATTN: Aliens!!!")

Yellow Python text

To add a background colour and a text colour:

- print(Fore.MAGENTA + "****************")

print(Fore.YELLOW + " Tonight Only!")

print(Back.CYAN + Fore.BLACK + "Party at Dave's")

print(Fore.MAGENTA + "****************")

Python multi colour code

To adjust the thickness of the text try:

- print(Fore.CYAN + Style.BRIGHT + "Sales & Inventory Management")

colorama style format

And that's it! It's up to you how you wish to use it. I found that it cheered my Python program up to engage the user and offer guidance if an input error occurred or confirmation if their input had been recorded. It also made debugging a lot more enjoyable and easier on the eyes when I had other colours to see, rather than continuous white text on a black background. Have fun!

Avatar for Amy Richardson

Written by Amy Richardson

Full Stack Software Development Student with the Code Institute. Loves building, making and creating.


Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.