This question already has answers here:
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
(14 answers)
Using global variables in a function
(25 answers)
Closed 2 years ago.
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)
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.
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.
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)
Related
This question already has answers here:
Variables declared outside function
(3 answers)
Closed 1 year ago.
I'm a newbie... and studying about global keyword.
This code creates a random string.
I think line 8, string.append(word[x]) make error on this code
because string is a global variable, so must be required global keyword. (global string)
But this code runs correctly...
Why can run correctly...?
import random
word = 'a b c d e f g h i j k l m n o p q r s t u v w x y z'.split(" ")
string = []
n = int(input())
def get(leng) :
for i in range (0, leng) :
x = random.randint(0, len(word)-1)
string.append(word[x])
sen = ''.join(string)
return sen
print(get(n))
Your code doesn't seem to have any problems at first look, although not very clear on what you want to be happening or the error, but in get(), your list string doesn't need to be assigned as a global variable unless you want to re-define the variable. If for whatever reason, you decide to declare string or any variable in that matter inside a funcion, you would need to change its scope.
This question already has answers here:
Using global variables in a function
(25 answers)
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
(14 answers)
Closed 2 years ago.
num = 0
def func():
print(num)
func()
The above function is supposed to print the value held by variable num and it works. By this, i would assume that func has access of num. But when i try to change the value of num inside the function, it gives me an error. UnboundLocalError: local variable 'num' referenced before assignment
num = 0
def func():
print(num)
num += 1
func()
Why is this happening?
The num variable isn't in the function's local scope, so you can't modify it inside the function since the variable contains an immutable data type (int).
You can take advantage of global keyword or define the variable inside the function.
num = 0
def func():
global num
print(num)
num += 1
func()
This question already has answers here:
How do I pass a variable by reference?
(39 answers)
Closed 2 years ago.
I want function(x) to change the value of whatever global variable is put into it, say add one to the variable, like so:
>>> a = 1
>>> function(a)
>>> print(a)
2
I tried:
def function(x):
global x
x = x + 1
However, this returns a SyntaxError name 'x' is parameter and global...
a=1 #global variable
def function():
global a
a=a+1 #operation on variable a
return a
function()
is this answer your query?
This question already has answers here:
Global dictionaries don't need keyword global to modify them? [duplicate]
(2 answers)
Why is the global keyword not required in this case? [duplicate]
(1 answer)
Closed 2 years ago.
I have declared a dictionary globally and a variable as well. Now, when accessing both in a class, I can access the dictionary but for accessing the other variable, I get the UnboundLocalError. For solving this, I used the line of code: global curr_length and then access it and it ran. But I wanted to known why is this additional line of code required for a normal integer variable whereas not required for a dictionary?
The code is:
memoized = {}
curr_length = 0
curr_pal = ""
class Solution:
def check_palindrome(self, str_):
if len(str_) <= 1:
return False
global curr_length
if len(str_) <= curr_length:
return False
if memoized.get(str_, None):
return memoized[str_]
if str_ == str_[::-1]:
memoized[str_] = True
curr_length = len(str_)
return True
memoized[str_] = False
return False
def longest_palindrome(self, str_, starting_index):
if len(str_) <= 1:
return None
n = len(str_)
if self.check_palindrome(str_[starting_index:n]):
return str_
n -= 1
self.longest_palindrome(str_[starting_index:n], starting_index)
def longestPalindrome(self, s: str) -> str:
for starting_index in range(len(s)):
pal = self.longest_palindrome(s, starting_index)
if pal:
return pal
return ""
solution = Solution()
print(solution.longestPalindrome("babad"))
Short:
You are trying to change the value of curr_length with curr_length = len(str_) inside a function which looks for a local curr_length variable, and can't find it. It needs the line global curr_length to know that it's a global variable.
As far as why you're wondering as to why a dict object does not need global memoized line, you should read the answer to:
Global dictionaries don't need keyword global to modify them? or Why is the global keyword not required in this case?
EXPLANATION:
In Python, a variable declared outside of the function or in global scope is known as global variable. This means, global variable can be accessed inside or outside of the function.
Let's see an example on how a global variable is created in Python.
x = "global"
def foo():
print("x inside :", x)
foo()
print("x outside:", x)
When we run the code, the will output be:
x inside : global
x outside: global
In above code, we created x as a global variable and defined a foo() to print the global variable x. Finally, we call the foo() which will print the value of x.
What if you want to change value of x inside a function?
def foo():
x = x * 2
print(x)
foo()
When we run the code, the will output be:
UnboundLocalError: local variable 'x' referenced before assignment
The output shows an error because Python treats x as a local variable and x is also not defined inside foo().
To make this work we use global keyword
This question already has answers here:
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
(14 answers)
Closed 4 years ago.
x = 5
def foobar():
print (x) #Prints global value of x, which is 5
x = 1 #assigns local variable x to 1
foobar()
Instead, it throws a
UnboundLocalError: local variable 'x' referenced before assignment
What am I misunderstanding in the comments? Note, I understand if i do x=x+1, it'll throw error due to 'accessing value of local scope x beforei it's defined', but in this case I'm doing x=1, which does not require reading of existing value of x! This is NOT a duplicate question.
If you want to change a global variables value in a function in python, you have to do
x = 5
def foobar():
global x
print (x) #Prints global value of x, which is 5
x = 1 #assigns local variable x to 1
foobar()