2015-04-07 108 views
1

我想用while循環getInput(myList)更改此嵌套列表遊戲板上的多個元素,但循環不會停止,當我輸入「Q」While循環修改多個元素嵌套循環

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

當進入「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()中額外打印,否則整個紙板將打印在一行上。