Pro Q
Pro Q

Reputation: 5016

How to use variable from previous scope in Python

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?

Upvotes: 2

Views: 143

Answers (1)

User2342342351
User2342342351

Reputation: 2174

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()

Upvotes: 3

Related Questions