Library Database - Python Programming Exercise

In this exercise, you will develop a Python program to create a small database for storing book data. For each book, you will keep the following information: Title and Author. The program must be able to store up to 1,000 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), and exit the program. This exercise is perfect for practicing the use of arrays and data manipulation in Python, as well as enhancing your skills in user interaction and database management. By implementing these functionalities, you will gain hands-on experience in handling user input and output in Python. This exercise not only reinforces your understanding of arrays and data manipulation but also helps you develop efficient coding practices for managing large datasets.

 Category

Arrays, Lists, and Strings

 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

 Copy 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

 More Python Programming Exercises of Arrays, Lists, and Strings

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  Enhanced Triangle V2

    In this exercise, you will develop a Python program that prompts the user for their name and displays a triangle with it, starting with 1 letter and growing until it ...

  •  Enhanced Rectangle V3

    In this exercise, you will develop a Python program that prompts the user for their name and a size, and displays a hollow rectangle with it. This exercise is ...

  •  Symmetrical Triangle

    In this exercise, you will develop a Python program that displays a centered triangle from a string entered by the user. This exercise is perfect for practicin...

  •  Urban Database

    In this exercise, you will develop a Python program to create a database for storing information about urban areas. In the first approach, you will store only the nam...

  •  Display Banner

    In this exercise, you will develop a Python program to mimic the basic Unix SysV "banner" utility, capable of displaying large texts. This exercise is perfect ...

  •  Right-Aligned Triangle

    In this exercise, you will develop a Python program that prompts the user for a string and displays a right-aligned triangle. This exercise is perfect for prac...