制作一个具有收藏书籍以及添加删除数据和推荐书籍的简易图书小程序代码
时间: 2024-04-08 11:31:06 浏览: 85
下面是一个简易的图书小程序的代码示例,包括收藏书籍、添加删除数据和推荐书籍的功能:
```python
# 导入必要的库
import random
# 图书列表
books = [
{"id": 1, "title": "Book 1", "author": "Author 1", "genre": "Genre 1"},
{"id": 2, "title": "Book 2", "author": "Author 2", "genre": "Genre 2"},
{"id": 3, "title": "Book 3", "author": "Author 3", "genre": "Genre 3"},
]
# 用户收藏的书籍列表
favorite_books = []
# 添加图书
def add_book(title, author, genre):
book_id = random.randint(1000, 9999)
book = {"id": book_id, "title": title, "author": author, "genre": genre}
books.append(book)
print("图书添加成功!")
# 删除图书
def delete_book(book_id):
for book in books:
if book["id"] == book_id:
books.remove(book)
print("图书删除成功!")
return
print("未找到该图书!")
# 收藏图书
def add_to_favorite(book_id):
for book in books:
if book["id"] == book_id:
favorite_books.append(book)
print("收藏成功!")
return
print("未找到该图书!")
# 推荐图书
def recommend_books():
random_books = random.sample(books, 3)
print("推荐图书如下:")
for book in random_books:
print(f"图书ID: {book['id']}, 标题: {book['title']}, 作者: {book['author']}, 类型: {book['genre']}")
# 主程序
def main():
while True:
print("欢迎使用图书小程序!")
print("1. 添加图书")
print("2. 删除图书")
print("3. 收藏图书")
print("4. 推荐图书")
print("0. 退出程序")
choice = input("请输入您的选择:")
if choice == "1":
title = input("请输入图书标题:")
author = input("请输入图书作者:")
genre = input("请输入图书类型:")
add_book(title, author, genre)
elif choice == "2":
book_id = int(input("请输入要删除的图书ID:"))
delete_book(book_id)
elif choice == "3":
book_id = int(input("请输入要收藏的图书ID:"))
add_to_favorite(book_id)
elif choice == "4":
recommend_books()
elif choice == "0":
print("谢谢使用!再见!")
break
else:
print("无效的选择,请重新输入!")
# 运行主程序
if __name__ == "__main__":
main()
```
请注意,这只是一个简单的示例代码,你可以根据你的需求进行修改和扩展。在实际开发中,你还需要考虑数据库等方面的实现。希望对你有所帮助!
阅读全文