python classic 100 questions to print chess board

The chess board is usually an 8x8 square with alternating black and white squares. The following are several code ideas and implementation methods for printing chess boards:

Method 1: Use for loop nesting

# 打印国际象棋棋盘
for i in range(8):
    for j in range(8):
        if (i + j) % 2 == 0:
            print("■", end =" ")  # 白色的格子
        else:
            print("□", end =" ")  # 黑色的格子
    print() # 换行

Method 2: Use list comprehensions

# 打印国际象棋棋盘
board = ['■' if ((i+j)%2 == 0) else '□' for j in range(8) for i in range(8)]
for i in range(0, 64, 8):
    print(' '.join(board[i:i+8]))

Method 3: Use the numpy library to generate an 8x8 matrix, and then loop through the output

import numpy as np

# 生成8x8的矩阵,0表示黑色,1表示白色
board = np.zeros((8,8), dtype=int)
board[::2, 1::2] = 1
board[1::2, ::2] = 1

# 输出矩阵中的值
for row in board:
    for value in row:
        if value == 1:
            print("■", end =" ")
        else:
            print("□", end =" ")
    print() # 换行

The above are several methods and code ideas for printing chess boards.

Guess you like

Origin blog.csdn.net/yechuanhui/article/details/132835269