Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Modify variable in scope of a function in another function in the same scope (Python)

I have a variable a whose scope is in function f().
There is another function b() in the scope of f(), where variable a is getting modified. How can I make sure the variable gets modified in function b() and is reflected correctly in the scope of function f()?

def f():
      a = 1
      def b():
             global a
             a = 2
      b()
      print(a)
 
f()

>>> 1  # expected is 2

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You must replace global to nonlocal.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading