Home > Mobile >  python if else with a Flag not working correctly
python if else with a Flag not working correctly

Time:11-27

Im trying to set a flag on my if else statement. I want it to be 1 if it crossover the upper thres but only the first cross after the previous signal and the same if it crossunder the lower thres (-1 on first cross under) . otherwise i want it to be 0.

So my logic is set a flag. Then on first sig cross (cond1) change the flag status... so it doesnt get triggered again.. but will now be able to trigger the signal cross under condition 2, otherwise its should be zero .. but it doens't work.

as is how i want
1 1
1 -1
1 1
1 -1
def is_triggered(row):
    flag = False
    
    if  flag == False and  ((row.D  >  row.UPPER) and (row.D_PREV < row.UPPER)) :
        return  1
    flag = True
    
    if  flag == True and ((row.D  <  row.LOWER) and (row.D_PREV > row.LOWER)):
         return -1
    flag = False
    
    return 0

CodePudding user response:

You have some state that isn't passed as an argument to the function.

One way to solve that would be to make a class to keep track of that state:

class ConditionTracker:
    def __init__(self):
        self.flag = False
    def test_trigger(self, row):
        if not self.flag and row.D > row.UPPER and row.D_PREV < row.UPPER:
            self.flag = True
            return 1
        elif self.flag and self.D < row.LOWER and row.D_PREV > row.LOWER:
            self.flag = False
            return -1
        return 0

You would then create an instance like so:

tracker = ConditionTracker()

And use it like so:

value = tracker.test_trigger(row)
#  value is now 1, -1 or 0
  • Related