How to output a numeric matrix in Python?

To output a number matrix, you can generate the matrix using nested loops and convert the numbers to strings using string formatting before outputting them.

Here is a sample code that can generate a number matrix of a specified size.

def print_number_square(size):
    for i in range(size):
        for j in range(size):
            print("{:2d}".format(i*size + j + 1), end=" ")
        print()

# 示例输出一个4×4的数字方阵
print_number_square(4)

The output result is:

 1  2  3  4 
 5  6  7  8 
 9 10 11 12 
13 14 15 16 

You can adjust the value of the size variable to generate number arrays of different sizes as needed.

bannerAds