Library Book Management System
BasicA comprehensive Python project for beginners
1) Project Overview
This project is a simple text-based program that helps manage a small library. You can:
- Add new books
- See all books
- Search for books by title or author
- Borrow a book
- Return a book
- Remove a book
It uses a menu that lets you choose what to do. It's perfect for practicing basic Python.
2) Learning Objectives
By building this project, students will learn:
- Variables, strings, integers, and booleans
- Lists and dictionaries to store data
- If/else decisions
- Loops (while and for)
- Functions to organize code
- Getting user input and simple validation
- Step-by-step problem solving
3) Step-by-Step Explanation
- Plan the data:
- Each book will be a dictionary with: id, title, author, year, available, borrower.
- All books will be stored in a list.
- Build a menu:
- Show options (1 to 7).
- Ask the user to enter a choice.
- Show all books:
- If the list is empty, say so.
- Otherwise, print each book nicely.
- Add a new book:
- Ask for title, author, and year.
- Give it a new id number.
- Set available = True and borrower = "" (empty).
- Search for books:
- Ask for a keyword.
- Show books where the title or author contains that keyword (case-insensitive).
- Borrow a book:
- Ask for the book id.
- If it exists and is available, mark it unavailable and store the borrower's name.
- If it's already borrowed, show a message.
- Return a book:
- Ask for the book id.
- If found and currently borrowed, mark it available again and clear the borrower's name.
- Remove a book:
- Ask for the book id.
- Confirm with the user before removing.
- Keep the program running:
- Use a while True loop to keep showing the menu until the user chooses Exit.
- Test:
- Try adding, searching, borrowing, returning, and removing books to make sure everything works.
4) Complete and Well-Commented Python Code
You can copy and run this code in any Python 3 environment.
# Our books will be stored as a list of dictionaries.
# Each book has: id, title, author, year, available, borrower
def show_menu():
print("\n======= Library Menu =======")
print("1) List all books")
print("2) Add a new book")
print("3) Search for books")
print("4) Borrow a book")
print("5) Return a book")
print("6) Remove a book")
print("7) Exit")
print("============================")
def get_int(prompt):
# Keeps asking until the user types a valid number
while True:
value = input(prompt).strip()
if value.isdigit():
return int(value)
else:
print("Please enter a whole number.")
def display_book(book):
# Prints one book in a friendly format
status = "Available" if book["available"] else f"Borrowed by {book['borrower']}"
print(f"[{book['id']}] {book['title']} - {book['author']} ({book['year']}) | {status}")
def list_books(books):
print("\n--- All Books ---")
if not books:
print("No books in the library yet.")
return
for book in books:
display_book(book)
def get_next_id(books):
# Finds the next id by looking for the current maximum
if not books:
return 1
max_id = max(b["id"] for b in books)
return max_id + 1
def add_book(books):
print("\n--- Add a New Book ---")
title = input("Title: ").strip()
author = input("Author: ").strip()
year = get_int("Year (e.g., 2005): ")
new_book = {
"id": get_next_id(books),
"title": title if title else "Untitled",
"author": author if author else "Unknown",
"year": year,
"available": True,
"borrower": ""
}
books.append(new_book)
print(f"Book added with id {new_book['id']}.")
def find_book_by_id(books, book_id):
for book in books:
if book["id"] == book_id:
return book
return None
def search_books(books):
print("\n--- Search Books ---")
keyword = input("Enter a keyword (title or author): ").strip().lower()
if not keyword:
print("You typed nothing. Try again.")
return
results = []
for book in books:
if keyword in book["title"].lower() or keyword in book["author"].lower():
results.append(book)
if not results:
print("No matching books found.")
else:
print(f"Found {len(results)} result(s):")
for book in results:
display_book(book)
def borrow_book(books):
print("\n--- Borrow a Book ---")
if not books:
print("There are no books to borrow.")
return
book_id = get_int("Enter the book id to borrow: ")
book = find_book_by_id(books, book_id)
if book is None:
print("No book with that id.")
return
if not book["available"]:
print(f"Sorry, this book is already borrowed by {book['borrower']}.")
return
name = input("Your name: ").strip()
if not name:
print("Name cannot be empty.")
return
book["available"] = False
book["borrower"] = name
print(f"You borrowed '{book['title']}'. Please return it later!")
def return_book(books):
print("\n--- Return a Book ---")
if not books:
print("There are no books to return.")
return
book_id = get_int("Enter the book id to return: ")
book = find_book_by_id(books, book_id)
if book is None:
print("No book with that id.")
return
if book["available"]:
print("This book is not borrowed right now.")
return
book["available"] = True
book["borrower"] = ""
print(f"Thank you for returning '{book['title']}'.")
def remove_book(books):
print("\n--- Remove a Book ---")
if not books:
print("There are no books to remove.")
return
book_id = get_int("Enter the book id to remove: ")
book = find_book_by_id(books, book_id)
if book is None:
print("No book with that id.")
return
display_book(book)
confirm = input("Are you sure you want to remove this book? (y/n): ").strip().lower()
if confirm == "y":
books.remove(book)
print("Book removed.")
else:
print("Removal canceled.")
def main():
# Start with a few sample books
books = [
{"id": 1, "title": "Matilda", "author": "Roald Dahl", "year": 1988, "available": True, "borrower": ""},
{"id": 2, "title": "The Hobbit", "author": "J.R.R. Tolkien", "year": 1937, "available": True, "borrower": ""},
{"id": 3, "title": "Harry Potter and the Sorcerer's Stone", "author": "J.K. Rowling", "year": 1997, "available": True, "borrower": ""}
]
while True:
show_menu()
choice = input("Choose an option (1-7): ").strip()
if choice == "1":
list_books(books)
elif choice == "2":
add_book(books)
elif choice == "3":
search_books(books)
elif choice == "4":
borrow_book(books)
elif choice == "5":
return_book(books)
elif choice == "6":
remove_book(books)
elif choice == "7":
print("Goodbye! Thanks for using the Library System.")
break
else:
print("Please choose a number from 1 to 7.")
# Run the program
if __name__ == "__main__":
main()
5) Output Examples
Example: Start and list books
1) List all books
2) Add a new book
3) Search for books
4) Borrow a book
5) Return a book
6) Remove a book
7) Exit
============================
Choose an option (1-7): 1
--- All Books ---
[1] Matilda - Roald Dahl (1988) | Available
[2] The Hobbit - J.R.R. Tolkien (1937) | Available
[3] Harry Potter and the Sorcerer's Stone - J.K. Rowling (1997) | Available
Example: Add a book
--- Add a New Book ---
Title: Holes
Author: Louis Sachar
Year (e.g., 2005): 1998
Book added with id 4.
Example: Search books
--- Search Books ---
Enter a keyword (title or author): harry
Found 1 result(s):
[3] Harry Potter and the Sorcerer's Stone - J.K. Rowling (1997) | Available
Example: Borrow a book
--- Borrow a Book ---
Enter the book id to borrow: 2
Your name: Alex
You borrowed 'The Hobbit'. Please return it later!
Example: Borrow the same book again
Choose an option (1-7): 4
--- Borrow a Book ---
Enter the book id to borrow: 2
Sorry, this book is already borrowed by Alex.
--- Borrow a Book ---
Enter the book id to borrow: 2
Sorry, this book is already borrowed by Alex.
Example: Return a book
Choose an option (1-7): 5
--- Return a Book ---
Enter the book id to return: 2
Thank you for returning 'The Hobbit'.
--- Return a Book ---
Enter the book id to return: 2
Thank you for returning 'The Hobbit'.
Example: Remove a book
Choose an option (1-7): 6
--- Remove a Book ---
Enter the book id to remove: 4
[4] Holes - Louis Sachar (1998) | Available
Are you sure you want to remove this book? (y/n): y
Book removed.
--- Remove a Book ---
Enter the book id to remove: 4
[4] Holes - Louis Sachar (1998) | Available
Are you sure you want to remove this book? (y/n): y
Book removed.
Example: Exit
Choose an option (1-7): 7
Goodbye! Thanks for using the Library System.
Goodbye! Thanks for using the Library System.
6) Small Exercise
Exercise 1: Add Statistics Feature
Add a new menu option called 8) Show statistics that prints:
- Total number of books
- Number of available books
- Number of borrowed books
Hint: Loop through the list and count how many have available == True.
Exercise 2: Edit Book Feature (Bonus)
After you master statistics, try adding an Edit a book option that lets the user change the title or author of a book by its id.
Steps:
- Ask for the book id
- Find the book
- Show current details
- Ask what to change (title, author, or year)
- Update the book with new information
Additional Challenge Ideas
- Add a due date feature for borrowed books
- Allow users to rate books (1-5 stars)
- Add categories/genres to books
- Save the library to a file (JSON) so data persists
- Add a feature to list only borrowed books or only available books
- Create a history log of all transactions
7) Summary
Great job! You built a real, working Library Book Management System. You practiced important coding skills like loops, decisions, functions, and working with lists and dictionaries. Keep experimenting—small improvements will teach you a lot. You're on your way to becoming a confident Python programmer!