0

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
Asmita Poddar
  • 524
  • 1
  • 11
  • 27

1 Answers1

1

You must replace global to nonlocal.

romanotpd
  • 121
  • 9