1

I was trying to create a class BookStack() where in I wanted that the user will enter book number and name as a list and it will get appended to a already created list, thus making a nested list. My code is as follows:

class BookStack():
    def __init__(self):
        self.books=[]

    def push(self,books):
        self.books.append(books)
        print self.books

    def pop(self):
        self.books.pop()

    def __str__(self):
        for i in self.books:
            print i,'\n'

def main():
    while 1:
        print "             1. Enter Book Credentials"
        print "     2. Remove the most recent book from database"
        print "                3. Print Database"

        choice=int(raw_input("Enter Choice: "))
        if(choice==1):
            book=BookStack()
            BookNumName=input("Enter Book Name & Number as [Number,Name]: ")
            book.push(BookNumName)
        elif(choice==2):
            book.pop()
        elif(choice==3):
            book.__str__()
        proceed=raw_input("Do you want to enter more(Y/N)?: ")
        if(proceed!='y' and proceed!='Y'):
            break

if __name__=='__main__':
    main()

But If I enter a list like [1,'A'] , [2,'B'] , [3,'C'], the output is

[[3, 'C']]

The output I want:

[[1,'A'],[2,'B'],[3, 'C']]    

1 Answer 1

2

You need to move the following out of the loop:

book=BookStack()

Instead, execute it once, before entering the loop.

You only want to create one BookStack. After that, just push new books onto it. If you recreate it, you are staring over with an empty BookStack.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, Tom :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.