# defining 3 variables in global scope
my_var1, my_var2, my_var3 = 10, 20, 30
def some_fun():
# declaring 'my_var1' as global inside a local scope,
# so now 'my_var1' can be modified for global scope
global my_var1
# accessing a global scope variable, works fine
print(my_var3)
# accessing a global scope variable defined as global, works fine
print(my_var1)
# but the same thing with 'my_var2' doesn't work, why?
# Note: comment below line to execute the program further
print(my_var2)
# Its because Python tries to figure out the scope of a variable by
# first seeing if it has some assignment in this scope if it does Python
# thinks it is a local variable, which we cannot access before
# assignment right? In below lines 'my_var2' has assignment,
# so it is considered as a local variable, even if same named global
# variable exists it will be considered as a local variable
# if the assignment is removed, 'my_var2' it will be considered global
# and it can be accessed normally
# modifying for global scope
my_var1 = 30
# modifying only for local scope
my_var2 = 40
# now calling the function
some_fun()
# let's check our global variables
print(my_var1, my_var2) # 30 \
# 10 \
# UnboundLocalError
# Notice: 'my_var1' is now changed but 'my_var2' is not
# similar to our previous example
def some_fun():
# defining 'my_var1' and 'my_var2' in local scope
my_var1 = 10
my_var2 = 20
def some_nested_fun():
# declaring 'my_var2' as nonlocal, so now it can be modified for
# 'some_fun()' scope too
nonlocal my_var2
# modifying for 'some_nested_fun()' scope
my_var1 = 30
# modifying for 'some_fun()' scope
my_var2 = 40
print(my_var1, my_var2)
# calling the nested function
some_nested_fun()
# Notice: Here 'my_var1' is not modified but 'my_var2' is
print(my_var1, my_var2)
# calling the outer function
some_fun() # 30 40 \
# 10 40