dark mode light mode Search Menu
Search

Python Rainbow

Marco Verch on Flickr

Farbige Markierungen

White text on a black background isn’t very snazzy! Let’s make our output more vibrant by injecting some rainbows into the console text.

THE TERMCOLOR LIBRARY

Open up a browser and navigate to www.repl.it/languages/python3. On the left hand, you’ll see your editor, where you write your code. On the right side is the console, where the results of the code are printed.

Start by importing the “colored” function from Python’s “termcolor” library. This function takes two arguments: the text you want to print, and a string describing the color of the text.

from termcolor import colored
text = colored("Hello world", "green")
print(text) 

Try it out by pressing the green “run” button at the top of the screen. You may noticed a paragraph of white text appearing in the console — that’s just the website tracking its installation of the termcolor library. Nothing to worry about! As long as your green “Hello world” text appears, your code is running fine.

Sadly, termcolor’s palette is pretty limited — nothing fancy like indigo or light fuchsia. The next step in our code is creating a list of all possible colours, in the order they appear in the rainbow:

colors = ['red', 'yellow', 'green', 'cyan', 'blue', 'magenta']

NOTE: for Python, you can use either single or double quotes for strings, as long as you open and close with the same one.

The result is a bit of a strange rainbow — cyan and magenta, but no purple or yellow — so let’s see how it looks printed out. To efficiently display our colours, we’ll use a structure called a “for each” loop. Double check that every open bracket has a closing bracket, and that your function arguments are properly nested.

for color in colors:  
  print(colored('X', color))
 print()

The loop goes through each color in the array, one at a time, first to last, and each time it runs the “print” statement with the current selected color. Since we have six elements in the array we run the loop six times.

If you want to print in a row instead of a column, add a second argument to your print function to specify that you don’t want to start a new line after the colourful ‘X’. Make sure to add the argument to the print function — not the colored function! — between the two closing brackets.

from termcolor import colored
colors = ['red', 'yellow', 'green', 'cyan', 'blue', 'magenta']

for color in colors:  
  print(colored('X', color), end="")
print()

MAKING THE RAINBOW ARC

Now that we’ve got our colors, let’s spread them out into a full rainbow. To make things simple, our rainbow will be drawn sideways. Start by printing out six identical rows of colored Xs using a nested for loop:

for n in range(len(colors)):
  for color in colors:  
    print(colored('X', color), end="")
  print()

The inner loop prints a single row. Since len(colors) — the length of the color array — is 6, the outer loop runs six times, one for each individual row.

To make this into an arc, we need each row to start a little further than the previous one. We can achieve this by adding spaces to the front of each line. Since the number of spaces increases with each row, we can use our “n” variable. On the first row, n = 0, and then on the next run n = 1, all the way to n = 5. Perfect!

for n in range(len(colors)):
  print(" " * n, end="") # print n spaces 
  for color in colors:  
    print(colored('X', color), end="")
  print()

Notice how the line that prints spaces is inside the outer loop, but not the inner one. The inner loop prints all six colors in a row, and we don’t want any pesky spaces getting between our pretty rainbow! What would happen if we put the print statement in the wrong space?

Typically, the outside of the rainbow is red, and the inside is purple. To achieve this in our code, we could rewrite the “colors” array to go in the opposite order. Luckily, a simpler solution exists! The “reverse” function creates a flipped array without modifying the original copy. Let’s sneak it into our code:

for n in range(len(colors)):
  print(" " * n, end="") # print n spaces
  for color in reversed(colors):   
    print(colored('X', color), end="")
  print()

To finish the rainbow, we want it to arc back downwards. Copy-paste the top block of code into your editor. All we need to change in the second block is the way spaces are printed — they should decrease instead of increasing. So instead of 0, 1, 2, 3, 4, 5, we want 5, 4, 3, 2, 1, 0.

To achieve this, simply switch “n” for (5-n). As “n” gets bigger, the resulting subtraction gets smaller, and just like that, we have our rainbow:

FULL CODE LISTING

from termcolor import colored
colors = ['red', 'yellow', 'green', 'cyan', 'blue', 'magenta']
 
for n in range(len(colors)):
 print(" " * n, end="")
 for color in reversed(colors): 
   print(colored('X', color), end="")
 print()
 
for n in range(len(colors)):
 print(" " * (5-n), end="")
 for color in reversed(colors): 
   print(colored('X', color), end="")
 print()

CONCLUSION

While printing colors is pretty and fun, they have a practical application as well. Console output is often used for debugging. By displaying the value of variables, programmers can see if their code is working the way they want. For programs with long outputs, colors can be used to code different types of errors, making them pop out from the rest of the display.

In the meantime, what cool pictures can you create with your newfound color skills?

Learn More

Nested loops in Python

https://www.tutorialspoint.com/python/python_nested_loops.htm

The termcolor library

https://pypi.org/project/termcolor/”

Using ASCII escape codes to add color in Python


http://ozzmaker.com/add-colour-to-text-in-python/”