2

I have a code in which I declare a variable globally. Then inside a function, when I try to use it, it gives an error Unbound variable is not declared My code:

count_url =1

def foo():
   ...
           ttk.Label(canvas1, text=f'{varSongTitle}...Done! {count_url}/{str(var_len)}').pack(padx=3,pady=3)
        root.update()
        count_url = count_url + 1

When I read from here that for bypassing this issue: The issue as I guess was that inside function my globally declared variable was becoming local, I guess because after printing it out I was assigning it to count_url =+ That's why I needed to also decalre it globally inside function as below:

count_url =1

def foo():
   global count_url
   ...
           ttk.Label(canvas1, text=f'{varSongTitle}...Done! {count_url}/{str(var_len)}').pack(padx=3,pady=3)
        root.update()
        count_url = count_url + 1

Now code works perfectly! But I have pair of questions How? Why?. Why it does not behave similarly if I assign global in global scope like

global count_url
count_url=1

def foo():
...

And also How can this be possible, that due to assigning inside the function a value to my global variable, why it becomes local?

1
  • Please do not edit questions to add an answer to them - that's not how Stack Overflow works. (I just found this duplicate question and closed it as a duplicate. By the way: my answer there already included the documentation link.) Commented Mar 31 at 22:07

1 Answer 1

3

The default behavior of Python is to create a new variable in the function scope without checking the global scope for a similarly named variable.

The global declaration inside the function tells Python that you want to use the variable declared in the outer scope instead of creating a new one.

Adding a reference to the official Python documentation, from a comment: https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value

Sign up to request clarification or add additional context in comments.

4 Comments

` use the variable declared in the outer scope` I thought declaring global inside function is for using it in outer scope. But, now your words describe it as, python looks for that variable in outer scope
Yes, you understood what I said correctly.
Thanks, I will also look for it in documentations

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.