Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to end the loop using a method? [duplicate]

Tags:

python

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()
like image 351
Ing Dedek Avatar asked Apr 16 '26 06:04

Ing Dedek


2 Answers

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
like image 93
RvdK Avatar answered Apr 18 '26 19:04

RvdK


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()
like image 37
Uyghur Lives Matter Avatar answered Apr 18 '26 18:04

Uyghur Lives Matter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!