Break outside loop Python function other options

爷,独闯天下 提交于 2019-12-31 03:46:10

问题


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?


回答1:


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')



回答2:


Replace break with return. break can only be used inside a loop, while return works anywhere in a function. The final code would look like this:

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


来源:https://stackoverflow.com/questions/18198172/break-outside-loop-python-function-other-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!