Code extract is below, I am trying to modify a variable in a nested function, I started out by practising modifying in a normal function and using the keyword 'global', however in a nested function I can only make it work by putting in global (highlighted in comment), but by doing this I am expanding the scope of the 'y' var outside the function bar, to the main program which is not what I want.
I only want the inner function foo to be able to see and modify 'y' but I do not want to make 'y' available to the main program.
Note I have already seen this post Using a global variable inside a function nested in a function in Python, however the question remains.
Thank you.
# accessing x outside scope is okay
x = 5
def bar():
print(x)
bar()
# modifying x outside scope needs global
x = 5
def bar():
global x
x = x+5
print(x)
# now original reference has been changed as well.
bar()
print(x)
# scope within nested functions
def bar():
global y ## why is this needed?
y = 5
print(f'y before foo called (): {y}')
def foo():
global y
y = y + 1
print(f'y in foo called (): {y}')
foo()
print(f'y after foo called (): {y}')
bar()
print(f'y outside function foo called (): {y}')
global yinbar(). You neednonlocal yinfoo()instead ofglobal y