我有一些代码:
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
开头,我希望它打破循环。每当我尝试时,都会收到错误消息:“打破”外循环
我怎样才能更好地编写它以使其正常工作?
最佳答案
正如马特·布莱恩特(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')