Library Book Management

Implement a class Library that maintains a private list of books. Include methods for adding, removing, and displaying books, and make sure that duplicate books can’t be added.

Example 1:

library = Library()
library.add_book("1984")
library.add_book("1984")
print(library.display_books()) 

Output: ["1984"]

Example 2:

library = Library()
library.add_book("To Kill a Mockingbird")
library.remove_book("The Great Gatsby")
print(library.display_books()) 

Output: ["To Kill a Mockingbird"]

Use a list to maintain the books and check for duplicates before adding a new book.

class Library:
    def __init__(self):
        self._books = []

    def add_book(self, book):
        if book not in self._books:
            self._books.append(book)

    def remove_book(self, book):
        if book in self._books:
            self._books.remove(book)

    def display_books(self):
        return self._books

# Test the class
library = Library()
library.add_book("1984")
library.add_book("1984")
print(library.display_books()) # Output: ["1984"]

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!