我有一些代码:
def playAgain1():
print("Would you like to keep boxing or quit while you are ahead? (y/n)")
playAgain = input().lower()
if(playAgain.startswith('y') == False):
print("Whatever you chicken.")
break
如果 playAgain()
不以 y
开头,我希望它打破循环。每当我尝试时,都会收到错误:
'break' outside loop
我怎样才能更好地编写它以使其发挥作用?
最佳答案
正如 Matt Bryant 的回答所述,您不能在循环之外中断,而只能从函数中返回。我想补充一点,您可能需要从函数返回一个值,以便主程序循环知道是返回开始还是退出:
def main():
while True:
# main game code goes here
if not playAgain():
break
def playAgain():
print("Would you like to keep boxing or quit while you are ahead? (y/n)")
response = input().lower()
return response.startswith('y')
关于python - 中断外部循环 Python 函数其他选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18198172/