Search code examples
pythonglobal-variablesmicropythonraspberry-pi-pico

If Function Being Triggered Despite Not Being Valid


For those who linked to Using global variables in a function How was I supposed to know this was related to my issue before hand? The reason I asked the question was that I didn't even know this (the global tag not the post) existed or applied to my issue.

I'm using a Raspberry Pi Pico and I'm getting a True or False value from a site I have setup. What ends up happening is I'll get isOn = True from my site, this triggers the first condition of the if statement. I turn isOperating to True so it will only run the if statement once. When I set isOn = False from my site, it triggers the second function only once and then defaults to the else statement.

I am confused why the first condition is ran multiple times despite the "print("isOn {0} and isOperating {1}".format(isOn, isOperating))" displaying the isOn is True and isOperating is True.

isOperating = False

def start():
    isOperating = True
    print('isOperating {0}'.format(isOperating))
    print('I am operating')

def stop():
    isOperating = False
    print('isOperating {0}'.format(isOperating))
    print('I am not operating')

print('Running...')
while True:
    r = urequests.get("aProperURL")
    jobject = r.json()
    isOn = jobject['isOn']

    if (isOn == True and isOperating == False):
        start()
        print("Start: I should print once!")
        print("isOn {0} and isOperating {1}".format(isOn, isOperating))
    elif (isOn == False and isOperating == True):
        stop()
        print("Stop: I should print once!")
        print("isOn {0} and isOperating {1}".format(isOn, isOperating))
    else:
        print("isOn is False and isOperating is False")

    time.sleep(2)

Solution

  • def start():
        isOperating = True
        print('isOperating {0}'.format(isOperating))
        print('I am operating')
    
    def stop():
        isOperating = False
        print('isOperating {0}'.format(isOperating))
        print('I am not operating')
    

    These functions did not declare isOperating to be global, therefore that variable is local in both of these functions, and the global one is not affected.