我有这个功能
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我需要知道一种方法,让这个函数在不中断或继续的情况下。
发布于 2015-04-09 01:35:40
我认为这应该可以做到:
...
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只有当rows不是True时才进入if块,如果在任何运行中,rows初始化为"q",那么while循环将在下一次运行时自动终止。
发布于 2015-04-09 01:21:26
您可以拥有一个保存布尔值True的变量,并且可以在所需的基本条件if rows == 'q':中转换为False。
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发布于 2015-04-09 02:21:59
如何使用else来避免需要continue。
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 myListhttps://stackoverflow.com/questions/29521184
复制相似问题