local variable referenced before assignment (CounterOne) - python

I ran the code before adding the CounterOne variable and it ran fine.
But after adding the CounterOne variable the compiler starts giving me below error.
"local variable 'CounterOne' referenced before assignment"
CounterOne = 0.00
def AAPILoad():
return 0
def AAPIInit():
return 0
def AAPIManage(time, timeSta, timeTrans, acycle):
AKIPrintString( "AAPIManage" )
xy = doSomething() #Read Number of Sections
for i in range (xy):
id = getID(i) #Read the identifier of a section
if (id==331):
xyz = DoCal(id,True) #Read the number of vehicles in a section
for j in range (xyz):
Calculaitons
if (0<=distanceFromTrafficLight<=300):
if ( condition == False) :
do calculations
else :
print ("Condition failed")
if ( Condition): #Cruising
Calval = 0.233+2*someValue
CounterOne = CounterOne + Calval
return 0

CounterOne
Is not a global variable, that is why the error is thrown.
You can either make it global, which is not recommended, or pass the CounterOne value to the function.
For global method:
def AAPIManage(time, timeSta, timeTrans, acycle):
global CounterOne
AKIPrintString( "AAPIManage" )
For function method :
def AAPIManage(time, timeSta, timeTrans, acycle,CounterOne):
AND RETURN CounterOne instead of zero

Related

UnboundLocalError error: local variable 'i' referenced before assignment

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

Python how to reference variable

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

How can I reference a global variable from within a function?

Hi I'm a beginner programmer. I don't know how can I call a variable from function.
I have two def calcular() and guardar(). I get some variables from calcular() that I will call later, but when I call variables in guardar(), it tells me that variable is not defined. I tried making global var, but it doesn't work. Hope you can help me
This is a little of my code...
def calcular():
if nClient == "":
texto = ("Inserta Numero de cliente")
ventanaMensaje(texto)
else:
if cl1=="":
texto = ("Inserta Clave")
ventanaMensaje(texto)
else:
if aB1 == "":
texto = ("Inserta Cantidad")
ventanaMensaje(texto)
else:
try:
clt = open("preciosEsp.txt","r+")
lClt = clt.readlines()
rClt = lClt[0]
sClt = rClt.split("'")
nRClt = sClt[0]
if nClient == nRClt:
cReg=sClt[1]
if cl1== cReg:
prc=sClt[2]
else:
k=1
while cl1 != cReg:
cReg=sClt[k]
k=k+2
if cl1== cReg:
ñ=k-1
prc=sClt[ñ]
else:
x = 0
while nClient != nRClt:
rClt = lClt[x]
sClt = rClt.split("'")
nRClt = sClt[0]
x=x+1
if nClient == nRClt:
cReg=sClt[1]
if cl1==cReg:
prc=sClt[2]
else:
k=1
while cl1 != cReg:
cReg=sClt[k]
k=k+2
if cl1== cReg:
ñ=k-1
prc=sClt[ñ]
indice=int(prc)+3
pdcts = open("productos.txt","r+")
lPdcts = pdcts.readlines()
rPdcts = lPdcts[0]
sPdcts= rPdcts.split("'")
nPdcts = sPdcts[0]
t = 0
if cl1 == nPdcts:
precio1=sPdcts[indice]
global txtD1################## MAKE A GLOBAL VAR
txtD1=sPdcts[1] #### THIS IS THE VARIABLE ########
def guardar():
guardarDatos = (n+txtD1) ################# I CALL HERE, BUT TELL ME THAT VARIABLE IS NOT DEFINED
If you really want a global variable, you'd define it outside of any function
txtD1 = None
def calcular():
...
it will then exist at module level. However, globals are rarely (read: never) the solution you should be using, instead you should be returning information from functions rather than modifying global state. You'd then pass that information into another function to use.
The global keyword in python says that you are referencing a global variable, not creating a new one. However, in your code no such name exists, so you're not actually referencing anything.
first create your "database" somewhere global
clt = dict(map(lambda x:x.split(" ",1),open("preciosEsp.txt","r+"))
now you can acess it anywhere with
clt.get(nClient)
next calcular should return the values you want
def calcular():
...
precio = clt.get(nClient)
return [precio,nClient,...]
then you would store the returned values (or do something with them as soon as they are returned )

python err: Local variable referenced before assignment

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

django module-level cache

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

Categories

Resources