How to end a loop with a method?

How do I force the while loop to end with a method?

class Test(object):

  def start(self):
    while True:
      self.stop()

  def stop(self):
    return break

obj=Test()
obj.start()

      

+3


source to share


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


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


class Test(object):

  def start(self):
    while not self.stop():
        pass

  def stop(self):
    return True

obj=Test()
obj.start()

      

or

class Test(object):

  def start(self):
    while True:
        if self.stop():
            break

  def stop(self):
    return True

obj=Test()
obj.start()

      

0


source







All Articles