简体   繁体   中英

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?

I keep getting the following error message:

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

I'm trying to program a stack data structure in python.

Here is my code:

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

You forgot to declare the variable global in functions where you change it.

For example:

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)

Variables in functions, if you assign to them, are considered local unless declared global (or nonlocal in Python 3).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM