当我将它声明为全局变量时,为什么我得到局部变量的错误,同时尝试在python中编写堆栈?

时间:2016-01-13 23:31:23

标签: python variables stack global local

我不断收到以下错误消息:

  

如果stack_pointer< max_length:UnboundLocalError:局部变量' stack_pointer'在分配前引用

我试图在python中编写堆栈数据结构。

这是我的代码:

stack_pointer = -1
stack =[]
max_length = 10

def view():
        for x in range (len(stack)):
            print(stack[x])
def push():
    if stack_pointer < max_length:
    item = input("Please enter the  item you wishto add to the stack: ")
    stack[stack_pointer].append(item)
    stack_pointer = stack_pointer + 1 
else:
     print("Maximum stack length reached!")

def pop():
    if stack_pointer < 0:
        print ("stack is empty!")
    else:
        item = stack[stack_pointer].pop(-1)
        stack_pointer = stackpointer - 1
        print ("you just popped out: ", item)

while True:
print ("")
print("Python implementation of a stack")
print("********************************")
print("1. view Stack")
print("2. Push onto Stack")
print("3. Pop out of Stack")
print("********************************")
print("")
menu_choice = int (input("Please enter your menu choice: "))
print ("")
print ("")

if menu_choice == 1:
    view()
elif menu_choice == 2:
    push()
elif menu_choice == 3:
    pop()

1 个答案:

答案 0 :(得分:1)

您忘记在更改它的函数中声明变量global。

例如:

def pop():
    global stack_pointer    # this is what you forgot
    if stack_pointer < 0:
        print ("stack is empty!")
    else:
        item = stack[stack_pointer].pop(-1)
        stack_pointer = stack_pointer - 1    # was a missing underscore here
        print ("you just popped out: ", item)

函数中的变量(如果分配给它们)被认为是本地变量,除非声明为全局变量(或Python 3中的非本地变量)。