How to declare variable in def() but not assign it every time

Viewed 39

what this code is doing is checking if i'm pressing INSERT button. And I want for it to write 100 or 144 every time I press it. So like first time it writes 100, second - 144, third - 100, and like that. So code is not working if I'm not assigning variable before "def starter():", but if I assign it after it will do that every 0.02 seconds, though I want it to assign variable once. So like var1 is assigning to 100 only at the first launch of code. How should I do that? Thanks for any feedback.

from win32api import GetKeyState
import threading
import time

def key_down(key):
        state = GetKeyState(key)
        if (state != 0) and (state != 1):
            return True
        else:
            return False

def starter():
    while True:
        if var2 != 3:
            var1 = 100
        if key_down(0x2D):
            print("pressed INSERT")
            if var1 == 100:
                var1 = 144
                var2 = 3
            else:
                var1 = 100
            print(var1)
            time.sleep(0.02)


def in_new_thread():
    th = threading.Thread(target=starter)
    th.start()

in_new_thread()
1 Answers

Something like this, untested:

from win32api import GetKeyState
import threading
import time

def key_down(key):
    state = GetKeyState(key)
    return state not in [0,1]

class Starter:
    def __init__(self):
        self.var1 = 100

    def run(self):
        while True:
            if key_down(0x2D):
                print("pressed INSERT")
                self.var1 = 244 - self.var1
                print(self.var1)
                time.sleep(0.02)

def in_new_thread():
    th = threading.Thread(target=Starter().run)
    th.start()

in_new_thread()
Related