当我将它声明为全局变量时,为什么在 python 中尝试对堆栈进行编程时会出现局部变量错误?

why am I getting an error of local variable when I have declared it as a global variable, whilst trying to program a stack in python?

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

if stack_pointer < max_length: UnboundLocalError: local variable 'stack_pointer' referenced before assignment

我正在尝试在 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()

您忘记在更改变量的函数中声明全局变量。

例如:

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 中为非局部变量)。