我试图使用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
答案 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()中额外打印,否则整个纸板将打印在一行上。