Skip to content
Advertisement

Comparing two values every n second and run a code based on the current and previous compared results in a while loop in python

Here is something I am trying to do:

A is a value that is constantly changing, and B is a fixed value

  1. compare A and B every 5 seconds
  2. if A > B, do something
  3. if A < B, do something else
  4. but if the current compared result is the same as the previous one (like if the current result is A > B, and the previous result is also A > B), do nothing until the result changes.
  5. repeat

I really don’t know what to do with the 4th one, could somebody give me a hint?

Huge thanks

Advertisement

Answer

As you have not mentioned any language preference, I am using python here.

import time
c = time.time()

if A>B:
    state = True
    ''' Do the initial action for this state'''
elif A<B:
    state = False
    ''' Do the initial action for this state'''
while True:
    if (time.time() - c) >= 5:
        c = time.time()
        A = check_A() # some dummy function for illustration purpose
        B = check_B() # some dummy function for illustration purpose
        if A>B:
            if not state:
                state = True
                ''' Do something that you like '''
        elif A<B:
            if state:
                state = False
                ''' Do something that you like '''

Here I have assumed that you do not want anything to happen when when A==B. The logic here that unless the state changes there will be no action for that particular state.

If here you do not want your code to be continuously running then you can use time.sleep(SLEEP_TIME).

import time

if A>B:
    state = True
    ''' Do the initial action for this state'''
elif A<B:
    state = False
    ''' Do the initial action for this state'''
while True:
    time.sleep(5)
    A = check_A() # some dummy function for illustration purpose
    B = check_B() # some dummy function for illustration purpose
    if A>B:
        if not state:
            state = True
            ''' Do something that you like '''
    elif A<B:
        if state:
            state = False
            ''' Do something that you like '''
Advertisement