-1

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)

3 Answers3

2

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.

quamrana
  • 37,849
  • 12
  • 53
  • 71
Arseniy
  • 680
  • 5
  • 10
1

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.

goalie1998
  • 1,427
  • 1
  • 9
  • 16
1

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)
Reid Moffat
  • 322
  • 1
  • 3
  • 16
  • 1
    "Global variables cannot be changed within functions" yes they can, if you use the global statement, but they probably shouldn't, and this is a better solution – juanpa.arrivillaga Jan 15 '21 at 21:20