简体   繁体   中英

Break out of a while loop using a function

Is there any way to break out of infinite loops using functions? Eg,

# 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.

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

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

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. Eg,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM