Implement a Library Management System in Python

Document 对象参考手册Python3 Examples

We will use Python to implement a simple library management system. This system allows users to add books, delete books, search for books, and display all books. We will use a dictionary to store book information, where the key is the ISBN number of the book, and the value is the detailed information of the book (such as title, author, etc.).

Example

class Library:
    def __init__(self):
        self.books = {}

    def add_book(self, isbn, title, author):
        if isbn in self.books:
            print("Book already exists!")
        else:
            self.books[isbn] = {'title': title, 'author': author}
            print("Book added successfully!")

    def delete_book(self, isbn):
        if isbn in self.books:
            del self.books[isbn]
            print("Book deleted successfully!")
        else:
            print("Book not found!")

    def find_book(self, isbn):
        if isbn in self.books:
            print(f"Book found: {self.books[isbn]}")
        else:
            print("Book not found!")

    def display_books(self):
        if not self.books:
            print("No books in the library!")
        else:
            for isbn, details in self.books.items():
                print(f"ISBN: {isbn}, Title: {details['title']}, Author: {details['author']}")

# Example usage
library = Library()
library.add_book("1234567890", "Python Programming", "John Doe")
library.add_book("0987654321", "Advanced Python", "Jane Smith")
library.display_books()
library.find_book("1234567890")
library.delete_book("0987654321")
library.display_books()

Code Analysis:

  1. LibraryClass: This is the core class of the library management system, containing the functions to add, delete, and search for books.
  2. __init__Method: Initialize an empty dictionaryself.booksto store book information.
  3. add_bookMethod: Add a book by ISBN number. If the ISBN number already exists, prompt that the book already exists.
  4. delete_bookMethod: Delete a book by ISBN number. If the ISBN number does not exist, prompt that the book was not found.
  5. find_bookMethod: Search for a book by ISBN number. If found, print the book information; otherwise, prompt that the book was not found.
  6. display_booksMethod: Display information of all books in the library. If there are no books, prompt that the library is empty.

Output result:

Book added successfully!
Book added successfully!
ISBN: 1234567890, Title: Python Programming, Author: John Doe
ISBN: 0987654321, Title: Advanced Python, Author: Jane Smith
Book found: {'title': 'Python Programming', 'author': 'John Doe'}
Book deleted successfully!
ISBN: 1234567890, Title: Python Programming, Author: John Doe

Document 对象参考手册Python3 Example

Other Extensions