228k views
1 vote
Write a Python program that collects information about the user's four favorite books. The program should collect the name of the book as well as the year they were published. The program should create a tuple for each book in the following format: ('book name', 'published year'), and then add all of the tuples to a list. Finally, The program should display the name of the oldest book (based on its published year) (Tip: If two book were published in the same year, the program should only display one of them.)

User Fabasoad
by
7.2k points

1 Answer

2 votes

Final Answer:

The program efficiently collects user input, organizes the information into tuples, identifies the oldest book based on publication year, and displays the result, adhering to the specified conditions.

Step-by-step explanation:

books_list = []

for _ in range(4):

book_name = input("Enter the name of the book: ")

published_year = int(input("Enter the year the book was published: "))

books_list.append((book_name, published_year))

oldest_book = min(books_list, key=lambda x: x[1])

print(f"The oldest book is '{oldest_book[0]}' published in {oldest_book[1]}.")

The Python program begins by initializing an empty list, books_list, to store tuples containing information about the user's favorite books. A loop prompts the user four times to input the name and publication year of each book, and these details are appended as tuples to the books_list.

To determine the oldest book, the program utilizes the min function with a custom lambda function as the key, focusing on the second element of each tuple (the published year). This identifies the book with the earliest publication year.

The final line then prints the name and publication year of the oldest book. If multiple books share the same oldest publication year, the program will display only one of them.

User Jplatte
by
8.0k points