Use Python to Implement a Library Management System
We will use Python to implement a simple library management system. The system allows users to add books, delete books, find books, and display all books. We will use a dictionary to store book information, where the key is the book's ISBN and the value is the book's detailed information (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
:
(
"Book already exists!"
)
else
:
self
.
books
[
isbn
]
=
{
'title'
: title
,
'author'
: author
}
(
"Book added successfully!"
)
def
delete_book
(
self
,
isbn
)
:
if
isbn
in
self
.
books
:
del
self
.
books
[
isbn
]
(
"Book deleted successfully!"
)
else
:
(
"Book not found!"
)
def
find_book
(
self
,
isbn
)
:
if
isbn
in
self
.
books
:
(
f
"Book found: {self.books[isbn]}"
)
else
:
(
"Book not found!"
)
def
display_books
(
self
)
:
if
not
self
.
books
:
(
"No books in the library!"
)
else
:
for
isbn
,
details
in
self
.
books
.
items
(
)
:
(
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:
Libraryclass: This is the core class of the library management system, containing functions to add, delete, and query books.__init__method: initialize an empty dictionaryself.booksto store book information.add_bookmethod: add a book by ISBN; if the ISBN already exists, prompt that the book already exists.delete_bookmethod: delete a book by ISBN; if the ISBN does not exist, prompt that the book was not found.find_bookmethod: find a book by ISBN; if found, print the book information, otherwise prompt that the book was not found.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
Python3 Examples