How To Format A Multiplication Table In Python

In this tutorial, you will learn how to format a multiplication table in Python. Creating a multiplication table is a common programming exercise to practice nested loops, and formatting a multiplication table further helps you familiarize yourself with Python’s string formatting capabilities.

By the end of this tutorial, you will know how to create and format a multiplication table using Python.

Step 1: Create a Basic Multiplication Table

First, let’s create a basic multiplication table using nested loops. In this example, we will create a 10×10 multiplication table.

This code snippet will generate the following multiplication table:

1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

Although this multiplication table is functional, it doesn’t look very nice. In the next step, we will format the table to make it more presentable.

Step 2: Format the Multiplication Table

To make the multiplication table look better, we will align the numbers using Python’s string formatting. We can use the .format() method to control the width of each number and make the multiplication table look more organized.

Update the print() statement inside the nested loop with the following line alongside your existing code:

With this change, the entire code snippet becomes:

Now, the formatted multiplication table will look like this:

  1  2  3  4  5  6  7  8  9 10
  2  4  6  8 10 12 14 16 18 20
  3  6  9 12 15 18 21 24 27 30
  4  8 12 16 20 24 28 32 36 40
  5 10 15 20 25 30 35 40 45 50
  6 12 18 24 30 36 42 48 54 60
  7 14 21 28 35 42 49 56 63 70
  8 16 24 32 40 48 56 64 72 80
  9 18 27 36 45 54 63 72 81 90
 10 20 30 40 50 60 70 80 90 100

The formatted multiplication table is easier to read and looks more organized. The {:3} inside the .format() method specifies that each number should take up 3 character spaces, which makes the table look aligned.

Conclusion

In this tutorial, you have learned how to create and format a multiplication table in Python using nested loops and string formatting.

With this knowledge, you can create more complex tables or modify the code to create multiplication tables of different sizes.

As a next step, you can explore more advanced formatting options using Python’s built-in format specification mini-language.