In this post,we are going to Write push(book) and pop(book) methods,in python to add books and remove books from list using list data structure.

Python program to write push(book) and pop(book) to add books and remove books from list

def isEmpty(stk):
    if stk == []:
        return True
    else:
        return False

def push(stk,item):
    stk.append(item)
    top = len(stk)-1
    
def pop(stk):
    if(stk==[]):
        print("Stack empty;UNderflow")
    else:
        print("Deleted Book is :",stk.pop())
    
def display(stk):
    if isEmpty(stk):
        print("Stack empty ")
    else :
        top = len(stk)-1
        print(stk[top],"<-top")
        for a in range(top-1,-1,-1):
            print(stk[a])
            
stack=[]
top = None
while True:
    print("STACK OPERATION:")
    print("1.ADD BOOK")
    print("2.Display STACK")
    print("3.REMOVE BOOK")
    print("4.Exit")
    ch = int(input("Enter your choice(1-4):"))
    if ch==1:
        bno = int(input("Enter BOOK No to be inserted :"))
        bname = input("Enter BOOK Name to be inserted :")
        item = [bno,bname]
        push(stack,item)
        input()
    elif ch==2:
        display(stack)
        input()
    elif ch==3:
        pop(stack)
        input()    
    elif ch==4:
        break
    else:
        print("Invalid choice ")
        input()

    
             


Output:

>>> %Run stackbook.py
STACK OPERATION:
1.ADD BOOK
2.Display STACK
3.REMOVE BOOK
4.Exit
Enter your choice(1-4):1
Enter BOOK No to be inserted :1
Enter BOOK Name to be inserted :LEARN PYTHON WITH 200 PROGRAMS

STACK OPERATION:
1.ADD BOOK
2.Display STACK
3.REMOVE BOOK
4.Exit
Enter your choice(1-4):1
Enter BOOK No to be inserted :2
Enter BOOK Name to be inserted :LET US PYTHON

STACK OPERATION:
1.ADD BOOK
2.Display STACK
3.REMOVE BOOK
4.Exit
Enter your choice(1-4):2
[2, 'LET US PYTHON'] <-top
[1, 'LEARN PYTHON WITH 200 PROGRAMS']

STACK OPERATION:
1.ADD BOOK
2.Display STACK
3.REMOVE BOOK
4.Exit
Enter your choice(1-4):3
Deleted Book is : [2, 'LET US PYTHON']

STACK OPERATION:
1.ADD BOOK
2.Display STACK
3.REMOVE BOOK
4.Exit
Enter your choice(1-4):2
[1, 'LEARN PYTHON WITH 200 PROGRAMS'] <-top

STACK OPERATION:
1.ADD BOOK
2.Display STACK
3.REMOVE BOOK
4.Exit
Enter your choice(1-4):4

Related python programs

Write a python program to implement a stack using list(Simple push and pop operations)

Write a python program to implement a stack for student using list data structure(menu-based program)

<

Leave a Reply

Your email address will not be published.