0

I do not succeed in keeping a running total throughout a Python program. I declare a variable at the beginning of the module, and increment it in a subsequent function. I always get the error message:

UnboundLocalError: local variable 'urls_checked' referenced before assignment.

The only time when I do not get that error is when I declare the running total inside the function check_url, but is nonsensical. Its value would each time reinitialize to 0.

Is it in this program not possible to keep a running total of the URLs checked?

Below I made a mockup very simplified version of the original program:

urls_checked = 0

def check_urls_in_page(html_page):
    for var in range(4): 
        check_url(var)

def check_url(url):
    # Check validity of url
    # and increase the running total
    # ...
    urls_checked +=1

if __name__ == "__main__":
    urls_checked = 0
    html_page = "somepage.html"
    check_urls_in_page(html_page)
    print("Urls checked: ",urls_checked)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • To format code blocks, use `\`\`\``, not `\``. – mkrieger1 Aug 27 '20 at 13:19
  • 1
    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) – mkrieger1 Aug 27 '20 at 13:26
  • Does this answer your question? [Don't understand why UnboundLocalError occurs (closure)](https://stackoverflow.com/questions/9264763/dont-understand-why-unboundlocalerror-occurs-closure) – Tomerikoo Aug 27 '20 at 13:38

2 Answers2

1

This is because you are currently accessing the variable locally however it has been declared globally, to fix this make sure you globalise your variable like so:

global urls_checked

Add that to the functions that use the urls_checked variable.

creed
  • 1,409
  • 1
  • 9
  • 18
0

The local namespace within the check_url() function does not include urls_checked as it is not a global variable, to reference it within the function use the global keyword:

urls_checked = 0

def check_url(url):
    global urls_checked
    urls_checked += 1
check_url()

print(urls_checked)
>>> 1
7koFnMiP
  • 472
  • 3
  • 17