打破外部循环Python函数其他选项 [英] Break outside loop Python function other options
本文介绍了打破外部循环Python函数其他选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些代码:
def playAgain1():
print(你想继续拳击吗? (y / n))
playAgain = input()。lower()
if(playAgain.startswith('y')== False):
print(无论你是鸡)
break
我希望它打破循环如果 playAgain()
不以 y
开头。每当我尝试,我得到的错误:
'break'outside loop
我怎么能写得更好,让它工作? 正如马特布莱恩特的答案指出的那样,你不能在循环外打破,但可以从函数返回。我会补充一点,你可能需要从你的函数中返回一个值,以便主程序循环知道是否返回到开始或退出:
def main():
而真:
#主游戏代码在这里
if playAgain():
break
(y / n))
response = input()。lower()
return()你打算如何继续拳击或退出? response.startswith('y')
I have some code:
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
I want it to break the loop if playAgain()
doesn't start with y
. Whenever I try, I get the error:
'break' outside loop
How could I write this better to make it work?
解决方案
As Matt Bryant's answer states, you can't break outside a loop but can just return from the function. I would add that you probably need to return a value from your function, so that the main programme loop knows whether to return to the start or quit:
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函数其他选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文