How to force to end the while loop using method?
class Test(object):
def start(self):
while True:
self.stop()
def stop(self):
return break
obj=Test()
obj.start()
You should keep a flag, and check that 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 immidiately then you will need to call break:
def start(self):
self.running = True
while self.running:
if self.stop():
break;
# do other stuff
The simplest way to achive this would be to raise and except a StopIteration. This will stop the loop immediately as opposed to 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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With