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)
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.
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.
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)
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)
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.
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.
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)