从键盘依次输入6本图书信息(以顺序表存放),分别编写按书号、书名及价格等信息的查找方法,实现图书信息的查找。的main方法
时间: 2024-02-11 09:05:18 浏览: 76
好的,以下是按照您的要求编写的代码:
```python
class Book:
def __init__(self, book_id, book_name, price):
self.book_id = book_id
self.book_name = book_name
self.price = price
class BookList:
def __init__(self):
self.book_list = []
def add_book(self, book):
self.book_list.append(book)
def search_by_book_id(self, book_id):
for book in self.book_list:
if book.book_id == book_id:
return book
return None
def search_by_book_name(self, book_name):
for book in self.book_list:
if book.book_name == book_name:
return book
return None
def search_by_price(self, price):
result = []
for book in self.book_list:
if book.price == price:
result.append(book)
return result
if __name__ == '__main__':
book_list = BookList()
for i in range(6):
book_id = input("请输入书号:")
book_name = input("请输入书名:")
price = input("请输入价格:")
book = Book(book_id, book_name, price)
book_list.add_book(book)
print("按书号查找:")
book_id = input("请输入要查找的书号:")
book = book_list.search_by_book_id(book_id)
if book:
print(f"书号为{book_id}的书信息为:{book.book_name},价格为{book.price}")
else:
print(f"没有找到书号为{book_id}的书")
print("按书名查找:")
book_name = input("请输入要查找的书名:")
book = book_list.search_by_book_name(book_name)
if book:
print(f"书名为{book_name}的书信息为:书号为{book.book_id},价格为{book.price}")
else:
print(f"没有找到书名为{book_name}的书")
print("按价格查找:")
price = input("请输入要查找的价格:")
books = book_list.search_by_price(price)
if books:
print(f"价格为{price}的书有以下几本:")
for book in books:
print(f"书号为{book.book_id},书名为{book.book_name}")
else:
print(f"没有找到价格为{price}的书")
```
以上代码实现了一个图书列表类 `BookList`,其中包含了添加图书、按照书号、书名、价格查找图书的方法。在 `main` 方法中,我们首先创建一个空的图书列表,并通过循环从键盘输入6本图书信息,并添加到图书列表中。接着,我们按照书号、书名、价格依次进行查找,并输出查找结果。
阅读全文