Home > Mobile >  How to save data in lists multiple time in python?
How to save data in lists multiple time in python?

Time:08-25

Hey I have been trying to create a simple book store program. When I am trying to print all the books that user has entered it is only showing one book data and not the others. Please help!

a = 1
while a == 1:
    title = input("Title: ")
    author = input("Author: ")
    purchase_price = float(input("Purchase_Price: "))
    sell_price = float(input("Sell_Price: "))
    continues = input("Do you want to enter more books? y/n")
    if continues == 'y':
        continue;
        book = [title,author,purchase_price,sell_price]
    elif continues == 'n':
        print(book)
        a = 0

CodePudding user response:

Well, because you are re-initiating the list again and again and also you are continuing before adding the book inside the list.

Instead of book = [title,author,purchase_price,sell_price] you may create an empty list above the while loop and append the book info inside this list. And you can then continue for next iteration.

Also, another thing is; you can use a basic class or a tuple structure inside the list in order to hold each book separately.

And one more thing; you don't need an integer (i.e. a = 1 for the while loop). Just continue with a boolean variable.

So, to sum up; you can use (or get along with it) following code:

flag = True
books = []
while flag:
    title = input("Title: ")
    author = input("Author: ")
    purchase_price = float(input("Purchase_Price: "))
    sell_price = float(input("Sell_Price: "))
    continues = input("Do you want to enter more books? y/n")

    book = (title,author,purchase_price,sell_price)
    books.append(book)
        
    if continues == 'n':
        print(books)
        flag = False

And for further steps; I recommend to add checks for the input fields as practice.

CodePudding user response:

Each time you insert a new book you are overriding the list "book".

You must use a different data structure, like a list of lists or (better) a list of dictionaries.

For example:

#List of dictionaries example
books=[]

while True:
    title = input("Title: ")
    author = input("Author: ")
    purchase_price = float(input("Purchase_Price: "))
    sell_price = float(input("Sell_Price: "))

    #At this point you insert the data in "books"
    books.append( {
        "title": title,
        "author": author,
        "purchase_price": purchase_price,
        "sell_price": sell_price
    })

    continues = input("Do you want to enter more books? y/n")
    if continues == 'y':
        continue;
    elif continues == 'n':
        
        #Print the content of the list of dictionaries
        for b in books:
            for key, value in b.items():
                print (f"{key} : {value}")
        print ("\n\n\n") #Just some empty lines...
        
        break # Exit the loop

CodePudding user response:

You need to instantiate a list before using it and then append an item to the list. reference. for example:

books = []
continues = "y"
while continues == "y":
    title = input("Title: ")
    author = input("Author: ")
    purchase_price = float(input("Purchase_Price: "))
    sell_price = float(input("Sell_Price: "))

    books.append((title, author, purchase_price, sell_price))

    continues = input("Do you want to enter more books? y/n")
    if continues == "n":
        print(books)

But if you want to know more about OOP, you can use class to resolve your problem. Like:

class Book:
    title: str
    author: str
    purchase_price: float
    sell_price: float

    def __init__(
        self, title: str, author: str, purchase_price: float, sell_price: float
    ):
        self.title = title
        self.author = author
        self.purchase_price = purchase_price
        self.sell_price = sell_price

    def __str__(self):
        return f"<Book: title={self.title}, author={self.author}, purchase_price={self.purchase_price}, sell_price={self.sell_price}>"

    def __repr__(self):
        return f"<Book: title={self.title}, author={self.author}, purchase_price={self.purchase_price}, sell_price={self.sell_price}>"

and then, you can create some book objects:

books = []
continues = "y"
while continues == "y":
    title = input("Title: ")
    author = input("Author: ")
    purchase_price = float(input("Purchase_Price: "))
    sell_price = float(input("Sell_Price: "))

    books.append(Book(title, author, purchase_price, sell_price))

    continues = input("Do you want to enter more books? y/n")
    if continues == "n":
        print(books)

This type of solution is useful when you want to validate some information, to add some behavior to the Book objects... etc

  • Related