You can download this code by clicking the button below.
This code is now available for download.
This function uses the PyInquirer library to get the category and genre of a book from the user, and then selects a matching book from a predefined list.
Technology Stack : PyInquirer
Code Type : Function
Code Difficulty : Intermediate
def select_random_book(title, author):
from pyinquirer import Prompt, Choice
questions = [
Choice(
name="category",
message="Please select the category of the book:",
choices=["Fiction", "Non-Fiction", "Science", "Biography", "Children's"]
),
Choice(
name="genre",
message="Please select the genre of the book:",
choices=["Mystery", "Romance", "Fantasy", "Historical", "Science Fiction"]
)
]
prompt = Prompt(questions)
answers = prompt.run()
selected_category = answers["category"]
selected_genre = answers["genre"]
book_list = [
"1984 by George Orwell",
"The Great Gatsby by F. Scott Fitzgerald",
"To Kill a Mockingbird by Harper Lee",
"The Catcher in the Rye by J.D. Salinger",
"Pride and Prejudice by Jane Austen",
"Moby Dick by Herman Melville",
"The Hobbit by J.R.R. Tolkien",
"The Lord of the Rings by J.R.R. Tolkien",
"Harry Potter and the Sorcerer's Stone by J.K. Rowling",
"The Diary of a Young Girl by Anne Frank"
]
book = [book for book in book_list if book.startswith(selected_category + " " + selected_genre)]
if book:
return book[0].split(" by ")[0] # Return the title of the selected book
else:
return "No book found matching the selected category and genre."