while循环在嵌套循环中修改多个元素

While loop to modify multiple elements in a nested loop

我正在尝试使用 while 循环 getInput(myList) 更改此嵌套列表游戏板中的多个元素,但当我输入 'q'

时循环不会停止
def firstBoard():
    rows = int(input("Please enter the number of rows: "))
    col = int(input("Please enter the number of columns: "))
    myList = [[0]*col for i in range(rows)]
    return myList
def getInput(myList):
    rows = input("Enter the row or 'q': ")
    col = input("enter the column: ")
    while rows != "q":
        rows = input("Enter the row or 'q': ")
        col = input("Enter the column: ")
        myList[int(rows)-1][int(col)-1] = "X"

    return myList

def printBoard(myList):
    for n in myList:
        for s in n:
            print(s, end= " ")

def main():
    myList = firstBoard()
    myList = getInput(myList)
    printBoard(myList)
main()

例如,如果我希望我的输出像这样结束:

X 0 0 0 0
0 X 0 0 0
0 0 X 0 0
0 0 0 0 0
0 0 0 0 0

当输入 'q' 时,您不会立即退出循环,而是试图转换为 int('q'),这会引发异常。您可以将其替换为:

def getInput(myList):
    while True:
        rows = input("Enter the row or 'q': ")
        if rows == 'q':
            break
        col = input("Enter the column: ")
        myList[int(rows)-1][int(col)-1] = "X"
    return myList

这也修复了您忽略第一个条目的事实。
您可能还需要在 printBoard() 中进行额外打印,否则整个板将打印在一行上。