Bring some colour to the console in this simple Python coding activity.
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()
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?
Nested loops in Python
The termcolor library
Using ASCII escape codes to add color in Python
Also In The December 2019 Issue
30+ ideas for STEAM-theme gifts for kids of all ages!
Bring some color to the console in this simple Python coding activity.
Ever wanted a cute, friendly pet? Now you can program your own!
Visual storytelling apps are a great way for kids to document and explore their lives.
Meet 16-year old Astronaut StarBright, whose activism is inspiring the next generation of STEM fans.
A cute name for a sneaky attack that can take down a website!
A step-by-step tutorial to build your very own virtual bird house in SketchUp!
Dive into the first “console wars” and learn how more bits led to bigger and better games.
From the start of computing history, people have tried to optimize the software programming process. This includes having two coders work together to code software.
Explore the solar system and test your knowledge of space through this fun coding activity.
Learn how procedural generation can be used to create infinite maps, music, and worlds to explore.
The Wayback Machine lets you travel back in time to see old websites. Plus the Internet Archive has thousands of vintage games, software, books, and more.
Online research skills are critical for software programmers. It's how you learn any language, by searching for error messages and looking up reference material.
How rural America connected itself to the phone grid using barbed wire, glass bottles, and even corncobs!
Meet Cozmo, the clever new robot that’s bringing AI concepts to life for kids as young as 5-7 years old.
Throw some festive ornaments on a virtual Christmas Tree in this fun introduction to functional programming.
How the Internet of Things could improve education, from VR to accessibility to facial recognition.
No one wants to deal with viruses over the holidays. Here’s how to protect your new devices!
Some digital tools to help you create your own unique, ever-changing symphony with nothing but some code and a computer!
Take a peek into the importance — and the struggle — of getting truly random data.
Interesting stories about computer science, software programming, and technology for December 2019.
Links from the bottom of all the December 2019 articles, collected in one place for you to print, share, or bookmark.