我有这个功能
def getInput(rows, cols, myList):
myList = [[0]*(cols-2) for i in range(rows-2)] #creates the board
for i in myList: # adds -1 to beginning and end of each list to make border
i.append(-1)
i.insert(0,-1)
myList.insert(0,[-1]*(cols)) #adds top border
myList.append([-1]*(cols)) #adds bottom border
while True:
rows = input("Please enter the row of a cell to turn on or 'q' to exit: ")
if rows == 'q': # if q then end while loop
break
cols = input("Please enter the column of a cell to turn on: ")
print()
myList[int(rows)][int(cols)] = 1 # changes chosen cells from 0(dead) to 1(alive)
return myList
我需要知道一种方法来使这个功能不间断或继续使用。
答案 0 :(得分:1)
我认为应该这样做:
...
rows = ""
while rows != 'q':
rows = input("Please enter the row of a cell to turn on or 'q' to exit: ")
if rows != 'q': # if q then end while loop
cols = input("Please enter the column of a cell to turn on: ")
print()
myList[int(rows)][int(cols)] = 1 # changes chosen cells from 0(dead) to 1(alive)
return myList
只有当行不为True时才进入if块,如果在任何运行中,行被初始化为"q"
,则while循环将在下一次运行时自动终止。
答案 1 :(得分:0)
您可以拥有一个包含布尔True
值的变量,并且可以在False
所需的基本条件下转为if rows == 'q':
。
status = True
while status:
rows = input("Please enter the row of a cell to turn on or 'q' to exit: ")
if rows == 'q':
status = False
continue
cols = input("Please enter the column of a cell to turn on: ")
print()
myList[int(rows)][int(cols)] = 1
return myList
如果您不想同时使用break
和continue
声明。比你应该返回myList
,因为它将从你的函数中退出,终止while循环。
if rows == 'q':
return myList
答案 2 :(得分:0)
如何使用else以避免需要继续。
def getInput(rows, cols, myList):
myList = [[0]*(cols-2) for i in range(rows-2)] #creates the board
for i in myList: # adds -1 to beginning and end of each list to make border
i.append(-1)
i.insert(0,-1)
myList.insert(0,[-1]*(cols)) #adds top border
myList.append([-1]*(cols)) #adds bottom border
run = True
while run:
rows = input("Please enter the row of a cell to turn on or 'q' to exit: ")
if rows == 'q': # if q then end while loop
run = False
else:
cols = input("Please enter the column of a cell to turn on: ")
print()
myList[int(rows)][int(cols)] = 1 # changes chosen cells from 0(dead) to 1(alive)
return myList