def func_print_x():
## x += 1 ## if uncomment this line, it will raise UnboundLocalError: local variable 'x' referenced before assignment
print x
if __name__ = '__main__':
x = 4
func_print_x()
In the function func_print_x(), there are two rules:
for the line 'x += 1', the variable x is regard as local variable;
when come to the line 'print x', the variable x seem to be global variable.
Does print function have more 'privilege'?
def f():
global s
print s
s = "That's clear."
print s
s = "Python is great!"
f()
print s
o/p
Python is great!
That's clear.
That's clear.
but whne you do not have global
def f():
print s
s = "Me too."
print s
s = "I hate spam."
f()
print s
o/p
UnboundLocalError: local variable 's' referenced before assignment
You will get the above error if you try to assign some values to s
if you try to print the value of s it will be printed inside the function
Related
In python I wrote:
registered_to = 0
def execute_data():
registered_to += response.text.count("<div class=\"info-msg\">")
But I'm getting:
registered_to += response.text.count("<div class=\"info-msg\">")
UnboundLocalError: local variable 'registered_to' referenced before assignment
Is this what you want?
registered_to = 0
def execute_data():
global registered_to
registered_to += response.text.count("<div class=\"info-msg\">")
global keyword must be used whenever you wish to modify/create global variables from a non-global scope like a function. If you are just using a global variable from a non-global scope and not modifying it, you need not use the keyword.
Examples
Using global variable in a non-global scope but not modifying it
wish = "Hello "
def fun():
print(wish)
fun()
Using global variable in a non-global scope and modifying it as well
wish = "Hello "
def fun():
word += "World"
print(wish)
fun()
I have tried to search this but I don't quite understand. I am coming across this error so I formed a quick easy example.
def test():
global a
a = 0
a+=1
def test2():
a+=1
print (a)
inp = input('a?')
if inp == 'a':
test()
test2()
When I input a. I expected the code to output 2. However, I get this error UnboundLocalError: local variable 'a' referenced before assignment. When I searched around about this, I found that you need to use global, but I already am using it.
So I don't understand. Can someone briefly explain what I'm doing wrong?
Thanks.
A global declaration only applies within that function. So the declaration in test() means that uses of the variable a in that function will refer to the global variable. It doesn't have any effect on other functions, so if test2 also wants to access the global variable, you need the same declaration there as well.
def test2():
global a
a += 1
print(a)
1) You can return the modified value like:
def test():
a = 0
a+=1
return a
def test2(a):
a+=1
print (a)
inp = input('a?')
if inp == 'a':
a = test()
test2(a)
2) Or you can use a class:
class TestClass:
a = 0
def test(self):
self.a = 0
self.a+=1
def test2(self):
self.a+=1
print (self.a)
Usage of option 2:
>>> example = TestClass()
>>> example.test()
>>> example.test2()
2
If I try to run the following code:
def func():
a = 5
print 'done'
return a
temp = raw_input('')
if temp == '':
func()
print func()
Say temp is '' and the function is run. It prints done and returns variable a. How can I print the returned variable without running the function once more, so done isn't printed again?
You should assign the returned value to a variable (e.g. a).
Update: you could either print inside the function (version1) or use global variable (version2)
def func():
a = 5
print 'done'
return a
# version 1: if print doesn't have to be outside of the function
def main():
temp = raw_input('')
if temp == '':
local_a = func()
else:
# use else to avoid UnboundLocalError: local variable 'a' referenced
# before assignment
local_a = None
print local_a
if __name__ == "__main__":
main()
# # version 2: if print have to be outside of the function, then I can only
# # think of using global variable, but it's bad.
# global_a = None
# def main():
# temp = raw_input('')
# if temp == '':
# global global_a
# global_a = func()
# if __name__ == "__main__":
# main()
# print global_a
You could use #zyxue's answer above and store the return value to a variable or you could also just not return anything from the function and just assign you final value in a function to a global variable if you have need for that.
I should warn you that it isn't good practice to overuse global variables unnecessarily or overly. See: https://stackoverflow.com/a/19158418/4671205
I get error UnboundLocal: Local variable T referenced before assignment, however it's not like that:
import ...
T = 0
def do_something():
do_something_else(T) # err at this line
T += 1
def do_something_else(t):
print t
do_something()
That is how my code looks, so it is not reference before assignment. (correct me if I am wrong) What's wrong?
Declare T as global variable:
def do_something():
global T # <--------------
do_something_else(T) # err at this line
T += 1
I am trying to store a value in a module level variable for later retrieval.
This function when called with a GET method throws this error: local variable 'ICS_CACHE' referenced before assignment
What am I doing wrong here?
ICS_CACHE = None
def ical_feed(request):
if request.method == "POST":
response = HttpResponse(request.POST['file_contents'], content_type='text/calendar')
response['Content-Disposition'] = 'attachment; filename=%s' % request.POST['file_name']
ICS_CACHE = response
return response
elif request.method == "GET":
return ICS_CACHE
raise Http404
I constructed a basic example to see if a function can read module constants and it works just fine:
x = 5
def f():
print x
f()
---> "5"
Add
global ISC_CACHE
as the first line of your function. You are assigning to it inside the function body, so python assumes that it is a local variable. As a local variable, though, you can't return it without assigning to it first.
The global statement lets the parser know that the variable comes from outside of the function scope, so that you can return its value.
In response to your second posted example, what you have shows how the parser deals with global variables when you don't try to assign to them.
This might make it more clear:
x = 5 # global scope
def f():
print x # This must be global, since it is never assigned in this function
>>> f()
5
def g():
x = 6 # This is a local variable, since we're assigning to it here
print x
>>> g()
6
def h():
print x # Python will parse this as a local variable, since it is assigned to below
x = 7
>>> h()
UnboundLocalError: local variable 'x' referenced before assignment
def i():
global x # Now we're making this a global variable, explicitly
print x
x = 8 # This is the global x, too
>>> x # Print the global x
5
>>> i()
5
>>> x # What is the global x now?
8