How to fix UnboundLocalError which I am getting in stack implementation?
Here is my code... this is code of stack implementation in python without using any class and i am getting error " top = top-1 UnboundLocalError: local variable 'top' referenced before assignment" and i don't understand what is the issue, How can I fix this?
S = []
top = None
def isEmpty(stak):
if(stak==[]):
return True
else:
return False
def push(stak, item):
stak.append(item)
top = len(stak)-1
def s_pop(stak):
i = stak.pop()
if(len(stak) == 0):
top = None
else:
top = top-1
return i
def peek(stak):
top = len(stak)-1
return stak[top]
def display(stak):
if(isEmpty(stak)):
print("Stack is empty")
else:
top = len(stak)-1
print(stak[top])
for i in range(top-1, -1, -1):
print(stak[i])
while True:
print("Implementation of Stack")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Exit")
choic = int(input("Enter the choice of operation you want to perform:"))
if(choic==1):
item = int(input("Enter the item you want to push:"))
push(S, item)
print('%d Push successfully' %item)
elif(choic == 2):
item = s_pop(S)
print('%d Pop successfully' %item)
elif(choic == 3):
item = peek(S)
print('%d' % item)
elif(choic == 4):
display(S)
elif(choic == 5):
break
else:
print("Enter a valid operation")