[英]Break outside loop Python function other options
我有一些代碼:
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
開頭,我希望它能打破循環。 每當我嘗試,我都會收到錯誤:
在外面循環'打破'
我怎么能寫得更好才能使它工作?
正如馬特布萊恩特的回答所說,你不能在一個循環之外突破,但可以從函數返回。 我想補充一點,您可能需要從函數中返回一個值,以便主程序循環知道是返回start還是退出:
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')
用return
break
。 break
只能在循環中使用,而return
只能在函數中的任何位置使用。 最終的代碼如下所示:
def playAgain1():
print("Would you like to keep boxing or quit while you are ahead? (y/n)")
playAgain = input().lower()
if not playAgain.startswith('y'):
print("Whatever you chicken.")
return
else:
# do whatever you do when they say yes
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.