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()
Related
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)
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()
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 5 years ago.
x=100
def fun2():
print x
x=10000
print x
fun2()
The above program showing local variable x reference before assignment. Why it is not printing
100
10000
x in the function is a local variable and can't access the other local variable you define first because they are in different scope.
Add global x to the start of your function or define x inside the function.
You appear to not know about variable scoping.
The variable x does not exist in the function scope.
You have to place global x before your print statement in order to access the global variable x.
x = 1 # Global x
def f():
x = 2 # function-local x
print(x) # prints 2
f()
print(x) # prints 1 because it uses the global x which remains unchanged
If you want that to work you need to specify inside the function that the x variable you are using is the one in the global scope by using the global keyword.
x=100
def fun2():
# Add this line
global x
print x
x=10000
print x
fun2()
Below code will print the value of x -> 100, as it is there in main scope #samba, but when you change the value of it doesn't work that way as it is not defined in the function.
x = 100
def fun2():
print(x)
fun2()
This doesn't work as the same way:
x = 100
def fun2():
print(x)
x = 1000
print(x)
fun2()
and through error:
UnboundLocalError: local variable 'x' referenced before assignment
x is a local variable and not initialised in function fun2().
You need to understand variable scoping here, Please check Global and Local variable scope
If you want to use it globally use global keyword in your function.
Because u assigned variable before function.
Just try this
def fun2():
x=100
print x
x=10000
print x
fun2()
It will output 100 and 1000