This code defines and implements a library management system that...

August 31, 2025 at 01:49 AM

import os import pickle class Book: """Represents a book in the library.""" def __init__(self, title, author, isbn): self.title = title self.author = author self.isbn = isbn self.is_borrowed = False def __str__(self): return f'"{self.title}" by {self.author} (ISBN: {self.isbn})' class Member: """Represents a library member.""" def __init__(self, name, member_id): self.name = name self.member_id = member_id self.borrowed_books = [] def __str__(self): return f'Member: {self.name} (ID: {self.member_id})' class Library: """Manages the books and members.""" def __init__(self, filename="library_data.pickle"): self.books = {} self.members = {} self.filename = filename self.load_data() def load_data(self): """Loads library data from a file.""" if os.path.exists(self.filename): with open(self.filename, 'rb') as f: data = pickle.load(f) self.books = data['books'] self.members = data['members'] print("Library data loaded successfully.") def save_data(self): """Saves library data to a file.""" with open(self.filename, 'wb') as f: data = {'books': self.books, 'members': self.members} pickle.dump(data, f) print("Library data saved successfully.") def add_book(self, title, author, isbn): """Adds a new book to the library.""" if isbn in self.books: print(f"Error: A book with ISBN {isbn} already exists.") else: new_book = Book(title, author, isbn) self.books[isbn] = new_book print(f'Added book: {new_book}') def register_member(self, name, member_id): """Registers a new library member.""" if member_id in self.members: print(f"Error: A member with ID {member_id} already exists.") else: new_member = Member(name, member_id) self.members[member_id] = new_member print(f'Registered member: {new_member}') def borrow_book(self, member_id, isbn): """Allows a member to borrow a book.""" member = self.members.get(member_id) book = self.books.get(isbn) if not member: print(f"Error: Member with ID {member_id} not found.") return if not book: print(f"Error: Book with ISBN {isbn} not found.") return if book.is_borrowed: print(f'Error: "{book.title}" is already borrowed.') return book.is_borrowed = True member.borrowed_books.append(book) print(f'"{book.title}" borrowed by {member.name}.') def return_book(self, member_id, isbn): """Allows a member to return a book.""" member = self.members.get(member_id) book = self.books.get(isbn) if not member: print(f"Error: Member with ID {member_id} not found.") return if not book: print(f"Error: Book with ISBN {isbn} not found.") return if book not in member.borrowed_books: print(f'Error: {member.name} did not borrow "{book.title}".') return book.is_borrowed = False member.borrowed_books.remove(book) print(f'"{book.title}" returned by {member.name}.') def list_all_books(self): """Lists all books in the library.""" if not self.books: print("The library is empty.") return print("\n--- All Books in the Library ---") for book in self.books.values(): status = "Borrowed" if book.is_borrowed else "Available" print(f"{book} - Status: {status}") def list_member_books(self, member_id): """Lists books borrowed by a specific member.""" member = self.members.get(member_id) if not member: print(f"Error: Member with ID {member_id} not found.") return print(f'\n--- Books borrowed by {member.name} ---') if not member.borrowed_books: print("No books borrowed.") else: for book in member.borrowed_books: print(f'- {book.title}') def run_cli(self): """Runs the command-line interface for the library system.""" while True: print("\n--- Library Management System ---") print("1. Add a new book") print("2. Register a new member") print("3. Borrow a book") print("4. Return a book") print("5. List all books") print("6. List books borrowed by a member") print("7. Save and exit") choice = input("Enter your choice: ") if choice == '1': title = input("Enter book title: ") author = input("Enter book author: ") isbn = input("Enter book ISBN: ") self.add_book(title, author, isbn) elif choice == '2': name = input("Enter member name: ") member_id = input("Enter member ID: ") self.register_member(name, member_id) elif choice == '3': member_id = input("Enter member ID: ") isbn = input("Enter book ISBN: ") self.borrow_book(member_id, isbn) elif choice == '4': member_id = input("Enter member ID: ") isbn = input("Enter book ISBN: ") self.return_book(member_id, isbn) elif choice == '5': self.list_all_books() elif choice == '6': member_id = input("Enter member ID: ") self.list_member_books(member_id) elif choice == '7': self.save_data() print("Exiting application.") break else: print("Invalid choice. Please try again.") if __name__ == '__main__': library = Library() library.run_cli()

This code defines and implements a library management system that allows for interactive command-line management of books and library members. Here's what the components and the overall code do:


Key Classes

  1. Book Class

    • Represents a book with attributes such as:
      • title: The title of the book.
      • author: The author of the book.
      • isbn: The ISBN (unique identifier) of the book.
      • is_borrowed: A flag indicating whether the book is currently borrowed (default: False).
    • __str__() provides a string representation of a book's details.
  2. Member Class

    • Represents a library member with attributes such as:
      • name: The name of the member.
      • member_id: A unique identifier for the member.
      • borrowed_books: A list of books currently borrowed by the member.
    • __str__() provides a string representation of a member's details.
  3. Library Class

    • Manages the overall system for books and members.
    • Key attributes:
      • books: A dictionary where keys are ISBNs and values are Book objects.
      • members: A dictionary where keys are member IDs and values are Member objects.
      • filename: A file to store library data using pickle for persistence.
    • Key methods:
      • Persistent Storage:
        • load_data(): Load books and members from a file if it exists.
        • save_data(): Save books and members to a file for persistence.
      • Book Management:
        • add_book(): Add a new book to the library by specifying its title, author, and isbn.
        • list_all_books(): List all available and borrowed books in the library.
      • Member Management:
        • register_member(): Register a new library member.
        • list_member_books(): List the books borrowed by a specific member.
      • Borrowing & Returns:
        • borrow_book(): Allows a member to borrow a book if it's available.
        • return_book(): Allows a member to return a previously borrowed book.
      • Command-Line Interface:
        • run_cli(): Provides an interactive command-line interface (CLI) for library management.

How It Works

  1. The program starts by creating an instance of the Library class (library = Library()).
  2. It executes the run_cli() method, allowing the user to interact with the system via a menu of commands.
  3. The user can:
    • Add books (add_book).
    • Register members (register_member).
    • Borrow/return books (borrow_book / return_book).
    • View all books or see what books a specific member has borrowed.
    • Save and exit, which writes the data to a file (pickle) for future sessions.
  4. All data (books and members) is stored in a file named library_data.pickle for persistent storage.

Features

  • Persistent Storage: Ensures the state of the library is retained after the program exits, using the pickle module to load and save the data.
  • Error Handling: Handles cases like adding duplicate books, nonexistent members or books, and attempting invalid borrowing/returns.
  • Interactive Menu: Provides an easy-to-use interface through the CLI.

Purpose

This code creates a basic library management system, helping librarians or operators to manage books and members directly through a command-line tool, with data persistence for convenience.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node