Break outside loop Python function other options

2020-04-26 13:39发布

问题:

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