2

I have the following code:

def test():
    def printA():
        def somethingElse():
            pass
        print(a)
        aHA = a[2]


    a = [1, 2, 3]
    while True:
        printA()

test()

I've noticed that this code will work fine, but if I change the aHA to just a, it says a is not defined.

Is there any way to set a to another value within printA?

Pro Q
  • 3,618
  • 3
  • 31
  • 74

1 Answers1

3

In python 3, you can set the variable as nonlocal

def test():
    a = [1, 2, 3]
    def printA():
        nonlocal a
        def somethingElse():
            pass
        print(a)
        a = a[2]

    while True:
        printA()

test()
Pierre Barre
  • 2,128
  • 1
  • 10
  • 22