Home > Software engineering >  Python showing local variable referenced before assignment
Python showing local variable referenced before assignment

Time:10-23

I've declared 2 variables the same exact way, but when I'm calling them stack is being referenced fine. But python is not able to reference top. What is the issue here?

def isValid(s):
    top=-1
    stack=[-1]*10005

    def push(x):
        print(top)
        top =1
        stack[top]=x
    push()

print(isValid(input()))

CodePudding user response:

The previous answer is mostly correct. Python considers any variable that you directly change the value of to be a local variable. Since you write top = 1, top is directly modified inside push, and is a local variable to push. The variable stack, on the other hand, is not changed.

I consider the fact that Python considers = operators to cause a variable to become local to be a bit of a bug. But it's too ingrained in the language.

And yes, the correct solution is to use nonlocal.

If you removed the top = 1 line, your code wouldn't work, but top would refer to the outer variable.

CodePudding user response:

Because push is indented inside isValid, it can't change the value of top from its "parent" function.

You can use nonlocal:

def isValid(s):
    top=-1
    stack=[-1]*10005

    def push(x):
        nonlocal top
        print(top)
        top =1
        stack[top]=x
  • Related