Random Book Selection Function

  • Share this:

Code introduction


The function randomly selects a book from a predefined list of titles and authors and returns the title and author of the book.


Technology Stack : The function uses the random library to randomly select a book from a predefined list of titles and authors.

Code Type : Function

Code Difficulty : Intermediate


                
                    
def select_random_book(title, author):
    import random
    books = [
        {"title": "The Great Gatsby", "author": "F. Scott Fitzgerald"},
        {"title": "1984", "author": "George Orwell"},
        {"title": "To Kill a Mockingbird", "author": "Harper Lee"},
        {"title": "Pride and Prejudice", "author": "Jane Austen"},
        {"title": "The Catcher in the Rye", "author": "J.D. Salinger"}
    ]
    selected_book = random.choice(books)
    return f"{title}: {selected_book['title']} by {selected_book['author']}"