我正在尝试在终端中打印井字棋板,并为用户提供选择板应该有多大的选项。 这是我的代码:
sq = [[" ", "|"],
[" ", "1", " ", "|",],
[" ", "|"],
["-------","|"]]
def square(board):
for row in board:
for slot in row:
print(slot, end="")
print()
number = int(input("How many squares do you want to board to be?n"))
for x in range(number):
square(sq)
问题是它们不会在一行上打印。我想打印行,然后打印列。我尝试在"for 循环"中添加end=""
,但这没有帮助。
有人可以向我解释我需要在我的代码中更改什么才能打印到同一行吗?
可能不是最好的方法,但是
sq = [[" ", "|"],
[" ", "1", " ", "|",],
[" ", "|"],
["-------","|"]]
def square(board, number):
for row in board:
for _ in range(number):
for slot in row:
print(slot, end="")
print()
number = 5
for x in range(number):
square(sq, number)
会给你你想要的。
您需要在第一行打印所有必需的行,然后使用print()
继续下一行。一旦你转到下一行,你就无法回头。
您可以删除插槽循环并将 x 循环带入行循环中,如下所示:
def square(board):
for row in board:
for x in range(number):
print(''.join(row),end='')
print()
只需在整个事情上添加另一个x循环,您就会拥有井字棋板:
def square(board):
for x in range(number):
for row in board:
for x in range(number):
print(''.join(row),end='')
print()