I'm getting a problem when referencing variables on a python file. Here is the code:
FG_E = 9
FG_R = 8
START = 7
READY = 9
MC = 3
BRAKE = 5
ERROR = 6
a = 2
b = 3
position = 0
def build_message(signal):
message = position
message = message | (0b1<<signal)
s = bin(message)
s = s[2:len(s)]
s = (16-len(s))*'0' + s
s0 = s[0:len(s)/2]
s1 = s[len(s)/2:len(s)]
s0 = s0[::-1]
s1 = s1[::-1]
s_final = int(s0 + s1, 2)
position = s_final
print bin(s_final)
return s_final
build_message(FG_R)
The error I get is:
UnboundLocalError: local variable 'position' referenced berofe assigment
The problematic line is actually position = s_final in the function build_message.
If it wasn't there then message = position would work because the Python interpreter would know to which position variable you are referring.
But in this case it is ambiguous because you're are later reassigning to position (position = s_final).
You should either re think the design of the code, or add global position as the first line in build_message. Keep in mind that as it says, it would make position a global variable and build_message will change the value of position every where throughout your code.
EDIT A quick demo:
global_var = 0
def foo1():
print(global_var)
def foo2():
print(global_var)
global_var = 1
def foo3():
global global_var
print(global_var)
global_var = 1
print(global_var)
foo1()
>> 0
foo2()
>> UnboundLocalError: local variable 'global_var' referenced before assignment
foo3()
>> 0
1
You need to use global keyword to access global variable.
def build_message(signal):
global position
message = position
If you are using an outside variable into a function maybe you should consider passing it as an argument, like:
def build_message(signal,position):
pass
Related
in the below code i am trying to understand the differences between global and local variables. At the runtime the following error is generated:#
File "m:\python lessons\globalAndLocal_1.py", line 21, in globalVsLocal_1
self.g2()
NameError: name 'self' is not defined
Note
i want to call g2 from within g1
please tell me how to call method g2()
code:
class globalVsLocal_1:
def f1(self):
global a #this is to reference a variable declared in the global context.
print ("f1 a = %s"%(a)) # if global a was not declared in the first line, generates this line an error as variable a not defined is
a = a + 10
print ("f1 a = %s"%(a))
def f2(self):
print("f2 a = %s"%(a))
def f3(self):
print("f3 b = %s"%(b))
#b = b + 1 #activating this line will yield an error. Because the absence of the keyword global. the print statement works immaculately without global keyword because it just reads the value without
#manipulate it
print("f3 b = %s"%(b))
def g1(self):
def g2():
print("g2 b = %s "%(b))
g2()
a = 1
b = 20
obj = globalVsLocal_1()
obj.f1()
obj.f2()
obj.f3()
obj.g1()
The scope of g2() is local to the function g1() so you cannot call it outside. It's also unusual that you try to call g2() in the middle of the class definition.
class ...
def g1(self):
def g2():
print("g2 b = %s "%(b))
g2()
class globalVsLocal_1:
def f1(self):
global a #this is to reference a variable declared in the global context.
print ("f1 a = %s"%(a)) # if global a was not declared in the first line, generates this line an error as variable a not defined is
a = a + 10
print ("f1 a = %s"%(a))
def f2(self):
print("f2 a = %s"%(a))
def f3(self):
print("f3 b = %s"%(b))
#b = b + 1 #activating this line will yield an error. Because the absence of the keyword global. the print statement works immaculately without global keyword because it just reads the value without
#manipulate it
print("f3 b = %s"%(b))
def g1(self):
def g2():
print("g2 b = %s "%(b))
g2()
a = 1
b = 20
obj = globalVsLocal_1()
obj.f1()
obj.f2()
obj.f3()
obj.g1()
You were missing indentation while called g2.
This gives the following output
f1 a = 1
f1 a = 11
f2 a = 11
f3 b = 20
f3 b = 20
g2 b = 20
I'm writing a program in selenium python. I pasted here part of the code from my program (I did not paste all the code because it has 800 lines) with the UnboundLocalError error: local variable 'i' referenced before assignment, the error occurs exactly at i += 1.
global i
i = 0
odpowiadanieobserwowaniestronfb0()
def odpowiadanieobserwowaniestronfb0():
if i > ileraz:
driver.quit
skonczono()
'''
try:
testt = driver.find_element_by_xpath('')
except Exception:
odpowiadanieobserwowaniestronfb1()
zleskonczono1()
'''
def odpowiadanieobserwowaniestronfb1():
i += 1
global keyword tells the function, not the whole module / file, what variables should be considered declared outside the scope of the said function. Try this:
def odpowiadanieobserwowaniestronfb1():
global i
i += 1
There are two options:
You can use your global variable:
def odpowiadanieobserwowaniestronfb1():
global i
i += 1
or you pass the i to the function:
def odpowiadanieobserwowaniestronfb1( i ):
return i += 1
I am trying to change variable using new_variable
variable = 10
new_variable = variable
new_variable += 1
print(new_variable)
print(variable)
I see that new_variable has changed while variable has not.
Is there a way to modify the value of variable using new_variable?
You can use class objects to get this behaviour.
class num:
def __init__(self,n):
self.n = n
variable= num(5)
newvariable = variable
newvariable.n = 3
print(variable.n)
print(newvariable.n)
Or you can use lists for the same
variable= [5]
newvariable = variable
newvariable[0] = 3
print(variable[0])
print(newvariable[0])
OUTPUT
3
3
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
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