Here's a well-documented and structured Python script that generates a neatly formatted multiplication table of a specified size. The script dynamically calculates the appropriate spacing based on the maximum value in the table to ensure all numbers are aligned properly.
✅ Multiplication Table Generator in Python
def generate_multiplication_table(n):
"""
Generates and prints an n x n multiplication table with proper alignment.
Parameters:
n (int): The size of the multiplication table (number of rows and columns).
"""
# Calculate the maximum product in the table (used to determine spacing)
max_product = n * n
# Determine the width of each cell based on the number of digits in the max product
# Add 1 to the width for better visual spacing
width = len(str(max_product)) + 1
# Print the header row (column headers)
print(f"{'':{width}}", end='') # Empty top-left cell for alignment
for col in range(1, n + 1):
print(f"{col:{width}}", end='')
print() # Newline after the header
# Print each row of the table
for row in range(1, n + 1):
print(f"{row:{width}}", end='') # Print the row number as the first column
for col in range(1, n + 1):
product = row * col
print(f"{product:{width}}", end='') # Print the product with proper spacing
print() # Newline after each row
# Example usage:
if __name__ == "__main__":
try:
size = int(input("Enter the size of the multiplication table: "))
if size < 1:
print("Please enter a positive integer.")
else:
generate_multiplication_table(size)
except ValueError:
print("Invalid input. Please enter a valid integer.")
📌 Explanation of Key Components
🧪 Example Output for n = 5
1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25
This format ensures that the table is easy to read and well-aligned, even for larger values of n.
📦 Optional Enhancements
- Add support for exporting the table to a file.
- Allow users to choose between different alignment options (left, center, right).
- Include color formatting or HTML table generation for web display.
This script is a robust and user-friendly way to generate multiplication tables in Python, suitable for educational or utility purposes.