Break out of a while loop using a function

2019-01-15 20:59发布

问题:

Is there any way to break out of infinite loops using functions? E.g.,

# Python 3.3.2
yes = 'y', 'Y'
no = 'n', 'N'
def example():
    if egg.startswith(no):
        break
    elif egg.startswith(yes):
        # Nothing here, block may loop again
        print()

while True:
    egg = input("Do you want to continue? y/n")
    example()

This causes the following error:

SyntaxError: 'break' outside loop

Please explain why this is happening and how this can be fixed.

回答1:

As far as I'm concerned you cannot call break from within example() but you can make it to return a value(eg : A boolean) in order to stop the infinite loop

The code:

yes='y', 'Y'
no='n', 'N'

def example():
    if egg.startswith(no):
        return False # Returns False if egg is either n or N so the loop would break
    elif egg.startswith(yes):
        # Nothing here, block may loop again
        print()
        return True # Returns True if egg is either y or Y so the loop would continue

while True:
    egg = input("Do you want to continue? y/n")
    if not example(): # You can aslo use "if example() == False:" Though it is not recommended!
        break


回答2:

The way to end a while-true loop would be to use break. Furthermore, the break must be in the immediate scope of the loop. Otherwise, you could utilize exceptions to hand control up in the stack to whatever code handles it.

Yet, oftentimes it's worth considering another approach. If your example is actually close to what you really want to do, namely depending on some user prompt input, I'd do it like this:

if raw_input('Continue? y/n') == 'y':
    print 'You wish to continue then.'
else:
    print 'Abort, as you wished.'


回答3:

An alternative way to break out of a function inside of a loop would be to raise StopIteration from within the function, and to except StopIteration outside of the loop. This will cause the loop to stop immediately. E.g.,

yes = ('y', 'Y')
no = ('n', 'N')

def example():
    if egg.startswith(no):
        # Break out of loop.
        raise StopIteration()
    elif egg.startswith(yes):
        # Nothing here, block may loop again.
        print()

try:
    while True:
        egg = input("Do you want to continue? y/n")
        example()
except StopIteration:
    pass