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

Question:

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
Asked By: Asmita Poddar

||

Answers:

You must replace global to nonlocal.

Answered By: romanotpd
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.