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

Question:

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)
Asked By: user15015324

||

Answers:

Variables that are created outside a function can be referenced to in the function without error, but can not be modified. You would have to make P global, define it in colorKeys, or pass it to colorKeys like you do key.

Answered By: goalie1998

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.

Answered By: Arseniy

Your function colorKeys(key) does not have a local variable P in it. Global variables cannot be changed within functions without the ‘global’ keyword (using the ‘global’ keyword is not recommended)

To fix this, you can return the value that you want to add to P:

def colorKeys(key):
    if key == keyK:
        return -2
    elif key == keyL:
        return 2
    return 0

P += colorKeys(key)
Answered By: Reid Moffat
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.