-1

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
AMC
  • 2,642
  • 7
  • 13
  • 35
Krystek
  • 35
  • 6
  • 1
    A "global" declaration must be repeated in each function which should use the global variable instead of a local one. – Michael Butscher Mar 17 '20 at 16:24
  • `i` is not within the scope of that last function. – de_classified Mar 17 '20 at 16:24
  • 2
    As a programmer you should try very, *very*, **very** hard not to use globals. – quamrana Mar 17 '20 at 16:30
  • **Please provide the entire error message, as well as a [mcve].** – AMC Mar 17 '20 at 16:49
  • Does this answer your question? [UnboundLocalError on local variable when reassigned after first use](https://stackoverflow.com/questions/370357/unboundlocalerror-on-local-variable-when-reassigned-after-first-use) – AMC Mar 17 '20 at 16:51
  • Also related: https://stackoverflow.com/questions/18002794/local-variable-referenced-before-assignment-in-python. – AMC Mar 17 '20 at 16:51

2 Answers2

0

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
sanitizedUser
  • 1,723
  • 3
  • 18
  • 33
0

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
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
MunsMan
  • 168
  • 1
  • 7