Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

import pickle

class Book:

def __init__(self, title, author, isbn, quantity):

self.title = title

self.author = author

self.isbn = isbn

self.quantity = quantity

self.available_quantity = quantity

class Library:

def __init__(self):

self.books = []

def add_book(self, book):

self.books.append(book)

def display_books(self):

for book in self.books:

print(f"{book.title} by {book.author} - Available: {book.available_quantity}")

def search_book(self, title):

for book in self.books:

if title.lower() in book.title.lower():

return book

return None

def borrow_book(self, title):

book = self.search_book(title)
if book and book.available_quantity > 0:

book.available_quantity -= 1

print(f"You have borrowed '{book.title}'. Enjoy your reading!")

elif book and book.available_quantity == 0:

print(f"Sorry, '{book.title}' is currently not available.")

else:

print(f"Book with title '{title}' not found.")

def return_book(self, title):

book = self.search_book(title)

if book:

book.available_quantity += 1

print(f"Thanks for returning '{book.title}'. We hope you enjoyed the book!")

else:

print(f"Book with title '{title}' not found.")

def save_library_data(self, filename):

with open(filename, 'wb') as file:

pickle.dump(self.books, file)

def load_library_data(self, filename):

try:

with open(filename, 'rb') as file:

self.books = pickle.load(file)

except FileNotFoundError:

print("Library data file not found. Starting with an empty library.")

def main():

library = Library()
library.load_library_data('library_data.pkl')

while True:

print("\nLibrary Management System Menu:")

print("1. Add Book")

print("2. Display Books")

print("3. Search Book")

print("4. Borrow Book")

print("5. Return Book")

print("6. Save and Quit")

choice = input("Enter your choice: ")

if choice == "1":

title = input("Enter book title: ")

author = input("Enter author name: ")

isbn = input("Enter ISBN: ")

quantity = int(input("Enter quantity: "))

new_book = Book(title, author, isbn, quantity)

library.add_book(new_book)

elif choice == "2":

library.display_books()

elif choice == "3":

search_title = input("Enter the title to search: ")

found_book = library.search_book(search_title)

if found_book:

print(f"Book found: {found_book.title} by {found_book.author}")


else:

print("Book not found.")

elif choice == "4":

borrow_title = input("Enter the title to borrow: ")

library.borrow_book(borrow_title)

elif choice == "5":

return_title = input("Enter the title to return: ")

library.return_book(return_title)

elif choice == "6":

library.save_library_data('library_data.pkl')

print("Library data saved. Exiting the program. Goodbye!")

break

else:

print("Invalid choice. Please try again.")

if __name__ == "__main__":

main()

Screenshots

You might also like