When I run the code, it says:
UnboundLocalError: cannot access local variable ‘selected’ where it is not associated with a value
Code:
import os
import time
import keyboard
selected = 1
options = 3
def draw():
print("I will finish this after getting up() and down() to work...")
pass
def up():
time.sleep(0.01)
os.system('cls' if os.name == 'nt' else 'clear')
if selected == 1:
selected = options
draw()
else:
selected += 1
print(selected)
pass
def down():
time.sleep(0.01)
os.system('cls' if os.name == 'nt' else 'clear')
if selected == options:
selected = 1
draw()
else:
selected -= 1
print(selected)
pass
keyboard.add_hotkey('up', lambda: up())
keyboard.add_hotkey('down', lambda: down())
keyboard.wait()
(Note: the draw() just print’s text for now so after getting up() and down() to work, I will then figure draw() out.
effigies
(Chris Markiewicz)
July 7, 2026, 2:27pm
2
def up():
+ global selected
time.sleep(0.01)
os.system('cls' if os.name == 'nt' else 'clear')
if selected == 1:
selected = options
draw()
else:
selected += 1
print(selected)
pass
def down():
+ global selected
time.sleep(0.01)
os.system('cls' if os.name == 'nt' else 'clear')
if selected == options:
selected = 1
draw()
else:
selected -= 1
print(selected)
pass
In the conditional statement:
if selected == 1:
it is referencing a variable that is neither global nor local.
peterc
(peter)
July 7, 2026, 2:30pm
4
This is happening because when Python compiles a function, if the function modifies any variables those variables are looked up in locals() instead of in globals(). You can override this behaviour with the global keyword as @effigies demonstrates.
gdchinacat
(Lonnie Hutchinson)
July 7, 2026, 2:44pm
5
codenowork7:
selected += 1
Variables that are assigned to are local to the function unless declared global or nonlocal. This ‘selected += 1’ (or -= in the other function) makes selected a local, and the ‘if selected …’ before this attempts to access an unbound local.
Something confusing about the message is that it points to the comparison (this was Python 3.14)
if selected == 1:
^^^^^^^^
UnboundLocalError: cannot access local variable 'selected' where it is not associated with a value
Removing the assignments and leaving the comparison, there is no error.