Python使函数不中断或继续
我有这个功能Python使函数不中断或继续,python,python-3.x,Python,Python 3.x,我有这个功能 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.inse
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
我需要知道一种不中断或继续执行此函数的方法。您可以拥有一个变量,该变量将保存布尔值
True
值,并且在所需的基本条件中,如果行=='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
我认为这应该做到:
...
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循环将在下一次运行中自动终止。如何使用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
向我们展示您的整个功能,然后
在循环时返回,或者在为True时重新考虑:
您能解释一下为什么不希望中断或继续?更多地了解您的实际约束将允许人们提供更好的答案。@Aroch1234如果您的查询得到解决,别忘了:)第二个有效,但我不能使用continue,我想知道你不想使用break
和continue
的原因。这是一个类,他们会因为使用break和continue而扣分。你应该在if条件中返回我的列表<代码>如果行=='q':返回myList
@Aroch1234如果有帮助,请提出并接受答案。谢谢