Colourful Formatted Tables in Python

This post is written for readers with different levels of experience with Python programming and also with Mathematics. Depending on your experience and interest, you will get different things from reading it. It contains a Python program for printing and neatly formatting coloured multiplication and addition tables, and includes coding DNA for achieving the following with Python programming:

  • Print text with coloured backgrounds and foregrounds in a console using Python
  • Create neatly formatted tables with just a few lines of code
  • Create multiplication and addition tables for “normal” arithmetic
  • Create and explore multiplication and addition tables for “finite arithmetics” formed by using the modulo operator
  • Pass operators as arguments to functions
  • Align and specify width of formatted strings

I’ll start by just sharing some code and then we’ll discuss what is does, how it does it and how to use it for your own purposes. You can access the code on or at the bottom of this post where I will provide the full listing.

Python program to display Multiplication and Addition tables – Online version

On one level, this is a tool to explore basic multiplication and addition tables in Python in colour, which could be useful in a teaching (or self-teaching) context. For a Python programmer though, it uses some very useful tools which you may want to incorporate into our own projects.

Coloured Text in the Console with The Python Colorama Module

To use this module you will need to intsall with pip instal colorama. You can find the module along with documentation here: Colorama. Below is a basic example of its usage.

from colorama import init, Fore, Back, Style


print(Fore.GREEN + 'green, '
      + Fore.RED + 'red, '
      + Fore.RESET + 'normal, '
      , end='')
print(Back.GREEN + 'green, '
      + Back.RED + 'red, '
      + Back.RESET + 'normal, '
      , end='')
print(Style.DIM + 'dim, '
      + Style.BRIGHT + 'bright, '
      + Style.NORMAL + 'normal'
      , end=' ')

This gives the following output in PowerShell:

Python coloured text in console

Some colors are different on PowerShell vs CMD, and also will appear different on different operating systems and environments. You may need to pick and choose from the available colours in order to maintain readability. The full list of available colours is:

BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET + some lighter versions made like LIGHTMAGENTA_EX from the basic colors just listed.

There are several more demos available on the github page for the project.

Printing Neatly Formatted Tables with the Python Tabulate Module

The Python Tabulate module module allows you to print neatly formatted tables without having to worry about manually positioning your data to make it clear and easily readable. It’s a pretty neat module and well worth experimenting with whenever you have tabular data you want to display in a console from a Python program.

from tabulate import tabulate

table = [["Sun", 696000, 1989100000], ["Earth", 6371, 5973.6], ["Moon", 1737, 73.5], ["Mars", 3390, 641.85]]
headers = ["Planet", "R (km)", "mass (x 10^29 kg)"]
print(tabulate(table, headers, tablefmt="pretty"))

| Planet | R (km) | mass (x 10^29 kg) |
|  Sun   | 696000 |    1989100000     |
| Earth  |  6371  |      5973.6       |
|  Moon  |  1737  |       73.5        |
|  Mars  |  3390  |      641.85       |

Passing Operators as function arguments

This is not something you can usually do without the help of an imported module. The operator module is our friend here. You can read about the available methods etc. here. In our program, we import just the names of the operators we need: add, mul, and pow, but many more are available.

Exploring Finite Arithmetics with Python Cayley Tables

This is usually a fairly advanced topic in Mathematics from a branch called Abstract Algebra, but actually anyone interested in modular arithmetic can use this tool to explore how the modulo operator works. The program create what are called Cayley Tables (Basically just multiplication/addition tables but for sets of elements other than just the set of all integers). The colour functionality provided by colorama makes it easy to see patterns in tables created with different values and operators. This can be a fascinating investigation for those whom enjoy this kind of thing. The full program is provided below.

Python Cayley Tables Program with Colour Display and Formatted Output

from tabulate import tabulate
from operator import add, mul, pow
from colorama import init, Back, Fore


def bin_op(a, b, op, mod):
    return op(a, b) % mod

def cayley_table(vals, mod, op=mul):
    if op == add:
        op_sign = "+"
    elif op == mul:
        op_sign = "*"
    elif op == pow:
        op_sign = "^"
        print("Operator not allowed.")
        raise SystemExit

    length = len(vals)
    headers = [op_sign]
    table = [[None] * length for _ in range(length)]
    for i in range(length):
        for j in range(length):
            val = bin_op(vals[i], vals[j], op, mod)
            color = BACKS[val % NUM_COLORS]  # Use several colours without running out.
            # color = BACKS[1] if val % 2 == 0 else BACKS[2]  # Simple even/odd color scheme
            table[i][j] = f"{color}{val:3}{Back.RESET}"
    print(tabulate(table, headers, tablefmt="pretty", showindex=row_ids))

if __name__ == "__main__":
    n = 5  # size of table
    # mod = n ** 2 + 1  # Full table no mod
    mod = n
    # vals = list(range(1, n + 1))  # no zeros, go all the way to n
    vals = list(range(n))
    row_ids = vals
    cayley_table(vals, mod, mul)  # options for final param are mul, add or pow

Python programming modulo table

So there you have it – lots going on in this article. Hopefully there will be something in there you can make use. Let me know in the comments if you found it helpful. Happy computing!

Sharing is caring!

Leave a Reply

Your email address will not be published. Required fields are marked *