-2

I used two techniques just to tackle this problem but was unable to resolve it. I want to modify the value of 'a' from 5 to 6 here but it is not modifying.

def f2():
    a=5
    def insidefun(c):
        if c==0:
            return
        if c==1:
            global a
            a=6
        return insidefun(c-1)
    insidefun(3)
    print(a)# result is 5 but I want to modify it to 6.global keyword is no working here
f2()

Another way I tried to do it by passing the value in function.

def f2():
    a=5
    def insidefun(c,a):
        if c==0:
            return
        if c==1:
            a=6
        return insidefun(c-1,a)
    insidefun(3,a)
    print(a) #still it is printing 5.
f2()

is there any way I can change the value of 'a' inside my function .

ILS
  • 1,224
  • 1
  • 8
  • 14
Amit
  • 1
  • 1

1 Answers1

0

using 'nonlocal a' I got the desired output.

def f2():
    a=5
    def insidefun(c):
        if c==0:
            return
        if c==1:
            nonlocal a
            a=6
        return insidefun(c-1)
    insidefun(3)
    print(a)
f2()
AlexK
  • 2,855
  • 9
  • 16
  • 27
Amit
  • 1
  • 1