我想把我的纸板印成菱形。所以前一行的缩进应该比下一行小。我该怎么做?

2024-09-27 21:35:16 发布

您现在位置:Python中文网/ 问答频道 /正文

global counter
global winner
def initBoard():
    global x
    global y
    x = int(input("Give x size for the board "))
    while x < 1 or x > 20:
        x = int(input("Please give a valid input (between 1 and 20) "))
    y = int(input("Give y size for the board "))
    while y < 1 or y > 20:
        y = int(input("Please give a valid input (between 1 and 20) "))
    i = 0
    j = 0
    global board
    board = [[0 for i in range(x)] for j in range(y)]

def showBoard():
    i = 0
    j = 0
    for i in range(1,1 + y):
        for j in range(1,1 + x):
            if j % x == 0:
                print("[", board [i-1] [j-1], "]", "\n")
            else:
                print("[", board [i-1] [j-1], "]", end="")

def setPiece():
    return 0

def play():
    initBoard()
    showBoard()

play()

我的代码到目前为止。还没有完成设定值的功能,所以不要强调这一点。Function initBoard请求用户尺寸并初始化电路板,Function showBoard应该打印电路板。它确实打印出来了,但我不知道如何像标题上描述的那样打印出来


Tags: ortheinboardforinputsizedef
1条回答
网友
1楼 · 发布于 2024-09-27 21:35:16

我相信这就是你想要的:

global counter
global winner


def initBoard():
    global x
    global y
    x = int(input("Give x size for the board "))
    while x < 1 or x > 20:
        x = int(input("Please give a valid input (between 1 and 20) "))
    y = int(input("Give y size for the board "))
    while y < 1 or y > 20:
        y = int(input("Please give a valid input (between 1 and 20) "))

    global board
    board = [[0 for i in range(x)] for j in range(y)]


def showBoard():
    for i in range(1, 1 + y):
        for j in range(1, 1 + x):
            if j % x == 0:
                print("[", board[i-1][j-1], "]", "\n")
                print(" " * i*3, end="")   # write a space depending on the row without line break
            else:
                print("[", board[i-1][j-1], "]", end="")


def setPiece():
    return 0


def play():
    initBoard()
    showBoard()

play()

我使用end=""来防止print语句后面的换行,该语句根据所处的行来设置一些空格。通过将因子i*3更改为其他值,可以调整斜率。啊,我还修改了格式。一定要阅读PEP 8 style guide for Python以获得可读和一致的代码格式

相关问题 更多 >

    热门问题