2016-01-13 48 views
1

我不斷收到以下錯誤信息:爲什麼當我將其聲明爲全局變量時嘗試在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() 

回答

1

你忘了聲明變量全球在你改變它的功能。

例如:

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外地)。

+0

謝謝,我剛剛得到它的工作,但我不得不這樣做:stack = [stack_pointer]這段代碼是什麼意思? –

+0

@lisaturner:'stack = [stack_pointer]'幾乎肯定是錯誤的。你拋棄了'stack',並用一個包含堆棧指針的全新'list'替換它,但沒有一個堆棧內容。 – ShadowRanger

+0

另外,不需要將'-1'傳遞給'list.pop';它已經從'list'的末尾默認彈出,所以傳遞它只是稍微增加參數解析開銷而不改變行爲。 – ShadowRanger

相關問題