How to end a loop with a method?
3 answers
You have to save the flag and check it in the while loop.
class Test(object):
def __init__(self):
self.running = False
def start(self):
self.running = True
while self.running:
self.running = not self.stop()
def stop(self):
return True
obj=Test()
obj.start()
If you want to stop immediately, then you will need to call break:
def start(self):
self.running = True
while self.running:
if self.stop():
break;
# do other stuff
+3
source to share
The easiest way to achieve this is to promote and exclude StopIteration
. This will stop the loop immediately, not RvdK's answer , which will stop at the next iteration.
class Test(object):
def start(self):
try:
while True:
self.stop()
except StopIteration:
pass
def stop(self):
raise StopIteration()
obj = Test()
obj.start()
+2
source to share