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
  • 4,391
  • 4
  • 43
  • 92

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,174
  • 1
  • 11
  • 23