I am currently working on my first program on python, however, when I've encountered a problem concerning the scope of definition of my variables. Here is the problematic sample of my code :
def listen(topLeft, bottomRight):
timeless = 0
# The key combination to check
COMBINATIONS = [
{keyboard.Key.shift, keyboard.KeyCode(char='b')}
]
# The currently active modifiers
current = set()
def execute():
global topLeft,bottomRight,timeless
print("Do Something")
if timeless == 0:
topLeft = mouse.position
timeless += 1
elif timeless == 1:
bottomRight = mouse.position
timeless += 1
elif timeless >= 2:
return False
def on_press(key):
global timeless
if any([key in COMBO for COMBO in COMBINATIONS]):
current.add(key)
if any(all(k in current for k in COMBO) for COMBO in COMBINATIONS):
execute()
def on_release(key):
if any([key in COMBO for COMBO in COMBINATIONS]):
current.remove(key)
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
Basically, once the Listener calls on_press, execute is called. In order to pass the timeless variable, I use the global tag. However, once the program comes to executing the execute function, I receive the following error code : NameError: name 'timeless' is not defined.
Any help would be appreciated, as I have tried pretty much everything I could
global timelessstatement has no effect onexecute; it just makes assignment totimelessinon_pressrefer to the global, rather than a local, variable.timelessis not a global; it's a local variable of thelistenfunction. Fix your indentation so we get a clearer idea of how your code is actually structured.executeis called everytimeon_pressis called, I cannot use a local variable, as it will re-declare it everytime (and it is the listener that callson_press).