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?
CodePudding user response:
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.