Implement a class Library
that stores a list of books. The class should have methods to add a book, remove a book, and search for a book by title or author.
Example 1:
Input: lib = Library() lib.add_book("Harry Potter", "J.K. Rowling") lib.add_book("The Great Gatsby", "F. Scott Fitzgerald") lib.search_book("Harry Potter") lib.remove_book("The Great Gatsby") lib.search_book("The Great Gatsby") Output: Book added Book added Book Found Book removed Book Not Found
Example 2:
Input: lib = Library() lib.add_book("1984", "George Orwell") lib.search_book("1984") lib.remove_book("1984") lib.search_book("1984") Output: Book added Book Found Book removed Book Not Found
The list data structure in Python can be used to store the books in the library. Each book can be represented as a dictionary with “title” and “author” as keys.
class Library: def __init__(self): self.books = [] def add_book(self, title, author): self.books.append({"title": title, "author": author}) print("Book added") def remove_book(self, title): for book in self.books: if book["title"] == title: self.books.remove(book) print("Book removed") return print("Book not found") def search_book(self, title): for book in self.books: if book["title"] == title: print("Book Found") return print("Book Not Found")
Unlock AI & Data Science treasures. Log in!