Search code examples
pythonpython-3.xcontinue

Python 3: Rerun the current function without any loop


I have a function called Cycle() which regulates what speed the pump should run based on temperatures. Here is a representation of it:

def Cycle(self, arg1, arg2, arg3, arg4):
   if arg1 < arg2:
       self.pumpSpeed = 100
   elif ....:
       print("Successfully cooled down. Returning to normal")
   elif ....:
       self.pumpSpeed = 45
   elif ....:
       print("Solar circuit cooled down. Returning to normal")
   elif ....:
       self.pumpSpeed = 0
   .
   .
   so on...

You can see in some conditions PumpSpeed is being set meanwhile in others just a print statement is provided and the system has to wait for the next cycle to decide what the PumpSpeed should be.

The way I run this is as follows:

for i in range(0,10):
    fetchNewArgs()
    Obj.cycle(arg1, arg2, arg3, arg4)
    sleep(5)

The problem is the system has to wait potentially 5 more seconds to decide what the new pump speed after cooling down should be.

The solution should be implementing a continue in the conditions required but the problem is this isn't a loop so can't.

Is there any way to run the Cycle() function immediately only in certain conditions without waiting 5 more seconds?

Based On @Quamrana's answers have to restrict the scope a bit more:

  1. The sleep time is variable and not always 5 so the part of returning sleep time increases complexity. If this was not the case, then definitely that would've worked.
  2. Important thing which apparently wasn't clear in the first statement. The reason I used the Rerun word is that I want to use the cycle with same arguments. Next time around, the arguments might've changed. Have revised the original loop function to demonstrate that.

Solution

  • Having changed the nature of the question, the function itself can be modified to also loop:

    def Cycle(self, arg1, arg2, arg3, arg4):
        do_loop = True
        while do_loop
            # ...
            elif ...:
                do_loop = False
            # ...
    

    The above works when most of the routes require a loop. Alternatively if most would like to exit, the do_loop flag can be reset within the loop:

    def Cycle(self, arg1, arg2, arg3, arg4):
        do_loop = True
        while do_loop
            do_loop = False
            # ...
            elif ...:
                do_loop = True
            # ...