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.
The way to end a while-true loop would be to use
break
. Furthermore, thebreak
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:
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 loopThe code:
An alternative way to break out of a function inside of a loop would be to raise
StopIteration
from within the function, and to exceptStopIteration
outside of the loop. This will cause the loop to stop immediately. E.g.,