UnboundLocalError error: local variable 'i' referenced before assignment - python

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

Related

using same variable that is created in function into another function

I want to use 'number' variable that was created out of the function and use it in couple functions and also give it an initial value 0, but it gives "local variable 'number' referenced before assignment" error at the last line of code.How could I fix it?Thanks in advance.
lst_img=[img0,img1,img2,img3,img4]
number=0
def go_forward():
global number
number+=1
shwimage.grid_forget()
global shwimage1
shwimage1=Label(image=lst_img[number])
shwimage1.grid(row=0,column=0,columnspan=3)
def go_back():
if number==0:
shwimage.grid_forget()
shwimage1.grid_forget()
shwimage2=Label(image=lst_img[number-1])
shwimage2.grid(row=0,column=0,columnspan=3)
number-=1 # local variable 'number' referenced before assignment
You have to also tell go_back() to use the global variable:
def go_back():
global number #add this
if number==0:
shwimage.grid_forget()
shwimage1.grid_forget()
shwimage2=Label(image=lst_img[number-1])
shwimage2.grid(row=0,column=0,columnspan=3)
number-=1 # local variable 'number' referenced before assignment
global tells the function to use the global number so each function has to be told this separately or it will default to using the local version.
I believe in go_back() function also, you are trying to reference the global variable number But it is not instructed to the function to use global number variable.
def go_back():
global number #This line needs to be addded
if number==0:
shwimage.grid_forget()
shwimage1.grid_forget()
shwimage2=Label(image=lst_img[number-1])
shwimage2.grid(row=0,column=0,columnspan=3)
number-=1
The others answers' solution to add global number in go_back is working, but using global variables is really not a good practice when you can do otherwise.
What you could do here is use object oriented programming. Create a class with a number, lst_img and showimage properties and two class methods, go_forward and go_backward, that can modifiy the number and showimage properties.
How I would start :
class ImageViewer:
# Class constructor
def __init__(self, lst_img):
self.lst_img = lst_img
self.number = 0 # number is always 0 at the beginning
self.showimage = None
def go_forward(self):
if self.number == len(self.lst_img)-1 :
return
else:
self.number += 1
# ... add your code ....
if self.showimage is None:
# code to create a showimage...
self.showimage = .....
else:
# code to update the showimage...
def go_backward(self):
if self.number == 0:
return
else :
self.number -= 1
if self.showimage is None:
# code to create a showimage...
self.showimage = .....
else:
# code to update the showimage...
# Create an viewer instance with a list of images
lst_img = [img1, img2, img3]
viewer = ImageViewer(lst_img)
# Now you can use the go_forward and go_backward methods to naviguate in your images
viewer.go_forward()
viewer.go_forward()
viewer.go_backward()
....
A reason you get the error, local variable 'number' referenced before assignment, is you did not used global keyword to declare that you will use THE number variable even in go_back().
A simple solution is to use global in the go_back(), as follows:
def go_back():
global number # -> as you did in `go_forward()`.
if number==0:
shwimage.grid_forget()
shwimage1.grid_forget()
shwimage2=Label(image=lst_img[number-1])
shwimage2.grid(row=0,column=0,columnspan=3)
number-=1 # local variable 'number' referenced before assignment
However, you need to play it safe when using global because it makes hard to track variable changes. Instead, it would be better to pass number value as an argument in the functions.
For more information to use global keyword, see an answer of the question here: Why are global variables evil?
In addition, I recommend you to read this article, Alternatives to Using Globals in Python
The problem is that you are using the number variable as global variable.
Use global number in both of your functions:
lst_img=[img0,img1,img2,img3,img4]
number=0
def go_forward():
global number
number+=1
shwimage.grid_forget()
global shwimage1
shwimage1=Label(image=lst_img[number])
shwimage1.grid(row=0,column=0,columnspan=3)
def go_back():
global number
if number==0:
shwimage.grid_forget()
shwimage1.grid_forget()
shwimage2=Label(image=lst_img[number-1])
shwimage2.grid(row=0,column=0,columnspan=3)
number-=1

Python UnboundLocalError, what causes it?

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()

local variable referenced before assignment (CounterOne)

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

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

Unbound Local Error with global variable [duplicate]

This question already has answers here:
Using global variables in a function
(25 answers)
Closed 7 months ago.
I am trying to figure out why I get an UnboundLocalError in my pygame application, Table Wars. Here is a summary of what happens:
The variables, REDGOLD, REDCOMMAND, BLUEGOLD and BLUECOMMAND, are initialised as global variables:
#Red Stat Section
REDGOLD = 50
REDCOMMAND = 100
#Blue Stat Section
BLUEGOLD = 50
BLUECOMMAND = 100
def main():
[...]
global REDGOLD
global REDCOMMAND
global BLUEGOLD
global BLUECOMMAND
This works when spawning units within the main loop, subtracting funds to spawn units.
Right now, I am trying to set up a system so that when a unit dies, the killer refunds the victim's COMMAND and earns GOLD based on what he killed:
class Red_Infantry(pygame.sprite.Sprite):
def __init__(self, screen):
[...]
self.reward = 15
self.cmdback = 5
[...]
def attack(self):
if self.target is None: return
if self.target.health <= 0:
REDGOLD += self.target.reward #These are the problem lines
BLUECOMMAND += self.target.cmdback #They will cause the UnboundLocalError
#when performed
self.target = None
if not self.cooldown_ready(): return
self.target.health -= self.attack_damage
print "Target's health: %d" % self.target.health
This works right up until the unit dies. Then this happens:
Traceback (most recent call last):
File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 606, in <module>
main()
File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 123, in main
RedTeam.update()
File "C:\Python27\lib\site-packages\pygame\sprite.py", line 399, in update
for s in self.sprites(): s.update(*args)
File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 304, in update
self.attack()
File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 320, in attack
REDGOLD += self.target.reward
UnboundLocalError: local variable 'REDGOLD' referenced before assignment
How do I get the global variables mentioned above to change with the attack block? If it helps, I am using Pygame 2.7.x, so nonlocal won't work :/
global make the global variable visible in the current code block. You only put the global statement in main, not in attack.
ADDENDUM
Here is an illustration of the need to use global more than once. Try this:
RED=1
def main():
global RED
RED += 1
print RED
f()
def f():
#global RED
RED += 1
print RED
main()
You will get the error UnboundLocalError: local variable 'RED' referenced before assignment.
Now uncomment the global statement in f and it will work.
The global declaration is active in a LEXICAL, not a DYNAMIC scope.
You need to declare the variable as global in each scope where they are being modified
Better yet find a way to not use globals. Does it make sense for those to be class attributes for example?
Found that variables in main act like global "read only" variables in function. If we try to reassign the value, it will generate error.
Try:
#!/usr/bin/env python
RED=1
A=[1,2,3,4,5,6]
def f():
print A[RED]
f()
It's ok.
But:
#!/usr/bin/env python
RED=1
A=[1,2,3,4,5,6]
def f():
print A[RED]
A = [1,1,1,1,1]
f()
Generate
File "./test.py", line 6, in f
print A[RED]
UnboundLocalError: local variable **'A'** referenced before assignment
and:
#!/usr/bin/env python
RED=1
A=[1,2,3,4,5,6]
def f():
print A[RED]
RED = 2
f()
Generate
File "./test.py", line 6, in f
print A[RED]
UnboundLocalError: local variable **'RED'** referenced before assignment

Categories

Resources