I ran the following code
global_var1 = 1
global_var2 = 2
def func():
print(global_var1)
print(global_var2)
global_var2 = 3
func()
It threw error
Traceback (most recent call last):
File "/home/harish/PycharmProjects/try/scope.py", line 10, in <module>
func()
File "/home/harish/PycharmProjects/try/scope.py", line 7, in func
print(global_var2)
UnboundLocalError: local variable 'global_var2' referenced before assignment
But the following code worked
__author__ = 'harish'
global_var1 = 1
global_var2 = 2
def func():
print(global_var1)
print(global_var2)
func()
My expectation was when the funcion func
was called. It would look for global_var1
and it was not it local so it looked in global and print it.
then similarly it would look for global_var1
and it was not it local so it looked in global and print it. then it would create a variable global_var2
in localscope and assign 3 .
May be it was not done like above because then within the same functions scope the same variable global_var2
had different meaning . till line 2 it was referring to global then there after local .. Is my guess correct ?