python 图书管理系统 代码
时间: 2023-09-08 11:12:21 浏览: 83
以下是一个简单的 Python 图书管理系统代码示例:
```python
class Book:
def __init__(self, title, author, pub_date):
self.title = title
self.author = author
self.pub_date = pub_date
class Library:
def __init__(self):
self.books = []
def add_book(self, book):
self.books.append(book)
def remove_book(self, book):
self.books.remove(book)
def search_book(self, title):
for book in self.books:
if book.title == title:
return book
return None
def display_books(self):
for book in self.books:
print(f"Title: {book.title}\nAuthor: {book.author}\nPublication Date: {book.pub_date}\n")
library = Library()
while True:
print("1. Add Book")
print("2. Remove Book")
print("3. Search Book")
print("4. Display All Books")
print("5. Quit")
choice = input("Enter your choice: ")
if choice == "1":
title = input("Enter book title: ")
author = input("Enter author name: ")
pub_date = input("Enter publication date (yyyy-mm-dd): ")
book = Book(title, author, pub_date)
library.add_book(book)
print("Book added successfully!\n")
elif choice == "2":
title = input("Enter book title: ")
book = library.search_book(title)
if book:
library.remove_book(book)
print("Book removed successfully!\n")
else:
print("Book not found!\n")
elif choice == "3":
title = input("Enter book title: ")
book = library.search_book(title)
if book:
print(f"Title: {book.title}\nAuthor: {book.author}\nPublication Date: {book.pub_date}\n")
else:
print("Book not found!\n")
elif choice == "4":
library.display_books()
elif choice == "5":
break
else:
print("Invalid choice!\n")
```
这个图书管理系统包含两个类:`Book` 和 `Library`。
`Book` 类包含书的标题、作者和出版日期。`Library` 类包含了一个空的书籍列表,并包含添加、删除、搜索和显示图书信息的方法。
程序使用一个无限循环来接受用户输入的选项。当用户输入 `1` 时,程序会提示用户输入书籍信息并将其添加到库存中。当用户输入 `2` 时,程序会提示用户输入书籍标题并从库存中删除该书籍。当用户输入 `3` 时,程序会提示用户输入书籍标题并显示该书籍的信息。当用户输入 `4` 时,程序会显示库存中所有书籍的信息。当用户输入 `5` 时,程序会退出循环,结束程序的运行。
阅读全文