title: Scope of variables in nested functions
body: <p>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.</p>
  <p>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.</p>
  <p>Note I have already seen this post <a href="https://stackoverflow.com/questions/51662467/using-a-global-variable-inside-a-function-nested-in-a-function-in-python">Using a global variable inside a function nested in a function in Python</a>, however the question remains.</p>
  <p>Thank you.</p>
  <pre><code># 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}')
  </code></pre>