Search code examples
pythonvariables

Says I haven't declared, even though I clearly have


The Error is called: UnboundLocalError: local variable 'P' referenced before assignment. I want it so I can change the Pen Width with K and L, but it won't let me. Can you help me?

from gturtle import*
keyK = 75
keyL = 76
P = 10

def colorKeys(key):
if key == keyK:
    P = P - 2
elif key == keyL:
    P = P + 2

makeTurtle(keyPressed = colorKeys)
hideTurtle()

while True:
    setPenWidth(P)

Solution

  • If you really want to use global variable in function, you can do this:

    def colorKeys(key):
      global P
      if key == keyK:
          P = P - 2
      elif key == keyL:
          P = P + 2
    

    But generally it is a bad idea.