Home > Blockchain >  while data == 1 run action one time
while data == 1 run action one time

Time:05-07

From an api, I receive a data. It returns two values: 1 and -1. I receive one data per second and in series of 1 or -1.

What I want is that when data goes to 1 you execute the action only once, and when it goes to -1 do the same action always once.

My problem is that for the moment I can't make the action happen only once. The action is repeated as long as data == 1 or data == -1

Moreover I need the code to continue to execute even if I'm not out of the loop.

Thanks for your help

signal_result = APIDATA

while signal_result == 1:
      self.action(signal_result)
                
while signal_result == -1:
      self.action(signal_result)

CodePudding user response:

Just keep track of the previous value, and if it is different, perform the action:

# at the very start, initialise 
previous_result = 0  # Some value that is different from 1 or -1

# ...
# ...

# When a signal is received:
    global previous_result
    signal_result = APIDATA
    if signal_result != previous_result:
        previous_result = signal_result
        self.action(signal_result)

  • Related