'How to have a if statement which is nested within a while statement only complete its function once

I'm trying to have my code only complete its process once. (If res = on only do it once but when it becomes off it detects that and does the off data encode once.) Here is my current code and my function onoff if needed as well

def onoff():
    result = firebase.get('/Data', 'Condition')
    return result

while True:
    res = onoff()
    data = res+","
    if res == 'on':
        ser.write(data.encode())
        print(data)
        time.sleep(1)
    elif ser.write(data.encode()):
        print(data)
        time.sleep(1)```


Solution 1:[1]

def onoff():
    result = firebase.get('/Data', 'Condition')
    return result
switch = True
while True:
    res = onoff()
    data = res+","
    if res == 'on' and switch:
        ser.write(data.encode())
        print(data)
        switch = False
        time.sleep(1)
    elif ser.write(data.encode()):
        print(data)
        time.sleep(1)```

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Doluk