用Python写一个图书管理系统
时间: 2023-12-24 07:07:18 浏览: 102
好的,下面是一个简单的图书管理系统的Python代码。它可以添加新书籍、删除旧书籍以及显示所有书籍的列表。你可以在此基础上进行更多的开发和改进。
```python
class Book:
def __init__(self, title, author, year, isbn):
self.title = title
self.author = author
self.year = year
self.isbn = isbn
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 display_books(self):
for book in self.books:
print(f"{book.title} by {book.author}, {book.year}, ISBN: {book.isbn}")
def main():
library = Library()
while True:
print("Select an option:")
print("1. Add a book")
print("2. Remove a book")
print("3. Display books")
print("4. Quit")
choice = input("Enter option number: ")
if choice == "1":
title = input("Enter book title: ")
author = input("Enter author name: ")
year = input("Enter publication year: ")
isbn = input("Enter ISBN number: ")
book = Book(title, author, year, isbn)
library.add_book(book)
print("Book added successfully.")
elif choice == "2":
title = input("Enter book title: ")
author = input("Enter author name: ")
year = input("Enter publication year: ")
isbn = input("Enter ISBN number: ")
book = Book(title, author, year, isbn)
try:
library.remove_book(book)
print("Book removed successfully.")
except ValueError:
print("Book not found in library.")
elif choice == "3":
library.display_books()
elif choice == "4":
print("Goodbye!")
break
else:
print("Invalid option. Please try again.")
if __name__ == "__main__":
main()
```
该程序定义了两个类,`Book` 和 `Library`。`Book` 类包含书籍的基本信息,如书名、作者、年份和ISBN号。`Library` 类包含一个书籍列表,并提供添加、删除和显示书籍的功能。
在 `main()` 函数中,用户可以选择执行四个选项之一:添加书籍、删除书籍、显示书籍列表或退出程序。根据用户的选择,程序将调用相应的方法来执行所需的操作。
注意,该程序没有实现持久化存储,因此在程序退出时所有数据都将丢失。如果需要更持久的存储,可以将数据保存到文件中。
阅读全文