Exercise
Library Database
Objective
Develop a Python program to create a small database for storing book data. For each book, we want to keep the following information:
- Title
- Author
The program must be able to store up to 1000 books, and the user will be allowed to:
- Add data for one book
- Display all entered books (just title and author, in the same line)
- Search for book(s) with a certain title
- Delete a book at a known position (for example, book number 6)
- Exit the program
Hint: to delete an item in an array, you must move backwards every item that was placed after it, and then decrease the counter.
Example Python Exercise
Show Python Code
# Crear una lista vacía para almacenar los libros
books = []
while True:
# Mostrar el menú de opciones
print("\nMenú:")
print("1. Agregar un libro")
print("2. Mostrar todos los libros")
print("3. Buscar un libro por título")
print("4. Eliminar un libro por número")
print("5. Salir")
# Solicitar al usuario una opción
option = input("Selecciona una opción (1-5): ")
if option == "1":
# Agregar un libro
title = input("Introduce el título del libro: ")
author = input("Introduce el autor del libro: ")
books.append((title, author))
print("Libro agregado exitosamente.")
elif option == "2":
# Mostrar todos los libros
if not books:
print("No hay libros disponibles.")
else:
print("\nTodos los libros:")
for i, (title, author) in enumerate(books, 1):
print(f"Libro {i}: {title} por {author}")
elif option == "3":
# Buscar un libro por título
title_to_search = input("Introduce el título a buscar: ")
found_books = [book for book in books if title_to_search.lower() in book[0].lower()]
if found_books:
print("\nLibros encontrados:")
for i, (title, author) in enumerate(found_books, 1):
print(f"Libro {i}: {title} por {author}")
else:
print("No se encontraron libros con ese título.")
elif option == "4":
# Eliminar un libro por número
if not books:
print("No hay libros para eliminar.")
else:
# Mostrar los libros antes de eliminar
print("\nLibros actuales:")
for i, (title, author) in enumerate(books, 1):
print(f"Libro {i}: {title} por {author}")
try:
book_number = int(input("Introduce el número del libro a eliminar: "))
if 1 <= book_number <= len(books):
books.pop(book_number - 1) # Eliminar el libro
print("Libro eliminado exitosamente.")
else:
print("Número de libro inválido.")
except ValueError:
print("Entrada inválida. Por favor, ingresa un número de libro válido.")
elif option == "5":
# Salir del programa
print("Saliendo del programa.")
break
else:
print("Opción inválida. Por favor, selecciona una opción entre 1 y 5.")
Output
Menu:
1. Add a book
2. Show all books
3. Search for a book by title
4. Delete a book by number
5. Exit
Select an option (1-5): 1
Enter the book title: Don Quixote
Enter the author of the book: Miguel de Cervantes
Book added successfully.
Menu:
1. Add a book
2. Show all books
3. Search for a book by title
4. Delete a book by number
5. Exit
Select an option (1-5): 1
Enter the book title: One Hundred Years of Solitude
Enter the author of the book: Gabriel García Márquez
Book added successfully.
Menu:
1. Add a book
2. Show all books
3. Search for a book by title
4. Delete a book by number
5. Exit
Select an option (1-5): 2
All books:
Book 1: Don Quixote by Miguel de Cervantes
Book 2: One Hundred Years of Solitude by Gabriel García Márquez
Menu:
1. Add a book
2. Show all books
3. Search for a book by title
4. Delete a book by number
5. Exit
Select an option (1-5): 3
Enter the title to search for: One
Books found:
Book 1: One Hundred Years of Solitude by Gabriel García Márquez
Menu:
1. Add a book
2. Show all books
3. Search for a book by title
4. Delete a book by number
5. Exit
Select an option (1-5): 4
Current books:
Book 1: Don Quixote by Miguel de Cervantes
Book 2: One Hundred Years of Solitude by Gabriel García Márquez
Enter the number of the book to delete: 1
Book deleted successfully.
Menu:
1. Add a book
2. Show all books
3. Search for a book by title
4. Delete a book by number
5. Exit
Select an option (1-5): 2
All books:
Book 1: One Hundred Years of Solitude by Gabriel García Márquez
Menu:
1. Add a book
2. Show all books
3. Search for a book by title
4. Delete a book by number
5. Exit
Select an option (1-5): 5
Exiting the program.
Share this Python Exercise