Creating a Neat Multiplication Table in Python

How can I create a properly formatted multiplication table in Python?

I am trying to make a multiplication table, but my current code outputs the results in a list format. Here is my current code:

n = int(input('Please enter a positive integer between 1 and 15: '))
for row in range(1, n + 1):
    for col in range(1, n + 1):
        print(row * col)
    print()

This correctly multiplies everything, but the output is not formatted as a neat table. I understand that I need to nest the loops and adjust the spacing, but I’m not sure how to do this.

How can I properly format the output of a multiplication table using Python multiplication table?

I’ve worked a lot with formatting in Python, and one simple way to align the table is to use string formatting. Here’s how you can do it:

n = int(input('Please enter a positive integer between 1 and 15: '))

# Format each element with a width for neat alignment
for row in range(1, n + 1):
    for col in range(1, n + 1):
        print(f"{row * col:4}", end=' ')  # 4 spaces wide for each number
    print()  # Move to the next row

This method ensures all numbers are aligned in columns, making it easier to read. Plus, it’s all native Python—no extra libraries required!

That’s a great approach, Ishrath! Another method I like using is the format() function for similar results. It keeps things clean and consistent. Here’s how to do it:

n = int(input('Please enter a positive integer between 1 and 15: '))

for row in range(1, n + 1):
    for col in range(1, n + 1):
        print("{:4}".format(row * col), end=' ')  # 4 spaces wide for each number
    print()  # Move to the next row

The output will look just as neat, but some people might find format() more intuitive than f-strings, especially if you’re working in older versions of Python. Both approaches are great for creating a Python multiplication table.

Good suggestions from Ishrath and Madhurima! For even more professional-looking output, I recommend using the tabulate library. It makes formatting large tables much easier and supports grid lines for added clarity. Here’s an example:

from tabulate import tabulate

n = int(input('Please enter a positive integer between 1 and 15: '))

# Create the multiplication table as a list of lists
table = [[(row * col) for col in range(1, n + 1)] for row in range(1, n + 1)]

# Print the table in a nicely formatted way
print(tabulate(table, tablefmt="grid"))

The output will include grid lines, making the table look professional and polished. You can install the library with pip install tabulate. It’s perfect for larger tables or when presentation matters.