使用 Python 实现一个图书馆管理系统
我们将使用 Python 实现一个简单的图书馆管理系统。该系统允许用户添加书籍、删除书籍、查找书籍以及显示所有书籍。我们将使用字典来存储书籍信息,其中键是书籍的 ISBN 号,值是书籍的详细信息(如书名、作者等)。
实例
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()
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()
代码解析:
Library
类:这是图书馆管理系统的核心类,包含书籍的增删查功能。__init__
方法:初始化一个空字典self.books
来存储书籍信息。add_book
方法:根据 ISBN 号添加书籍,如果 ISBN 号已存在则提示书籍已存在。delete_book
方法:根据 ISBN 号删除书籍,如果 ISBN 号不存在则提示书籍未找到。find_book
方法:根据 ISBN 号查找书籍,如果找到则打印书籍信息,否则提示书籍未找到。display_books
方法:显示图书馆中所有书籍的信息,如果没有书籍则提示图书馆为空。
输出结果:
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
点我分享笔记