Break out of a while loop using a function

房东的猫 提交于 2019-11-28 02:14:14

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