This project guides you through building a simple, console-based Library Management System using Python and SQLite. Designed for beginners, this application allows librarians to efficiently manage their book collection and track borrowing/returning activities. You’ll learn fundamental programming concepts, database interaction, and how to create a practical, interactive command-line application.
Table of Contents
Features of the Project
- Add New Books: Librarians can add new books to the library’s collection with details like title, author, ISBN, and quantity.
- List All Books: Display a comprehensive list of all books currently in the library, including their availability status.
- Borrow a Book: Users can borrow an available book, which updates its quantity and records the transaction.
- Return a Book: Users can return a borrowed book, increasing its available quantity.
- Search for Books: Find books by title or author to quickly check their availability and details.
- Simple Console Interface: Interact with the system through a user-friendly text-based menu.
- Data Persistence: All book and transaction data is stored permanently using a SQLite database.
Technologies / Tools Used (Tech Stack)
- Programming Language: Python 3.14 (or later)
- Database: SQLite3 (built-in Python module)
- Optional Library for Table Formatting: Tabulate (for cleaner console output)
System Requirements
- Operating System: Windows, macOS, or Linux.
- Python Interpreter: Python 3.14 or a newer stable version installed on your system.
- Integrated Development Environment (IDE): Any Python-compatible IDE like VS Code, PyCharm, or a simple text editor.
- Dependencies: The `sqlite3` module is built-in with Python. If you choose to use `tabulate` for better table formatting, you’ll need to install it:
pip install tabulate.
Project Workflow / Architecture
This Library Management System follows a simple client-server-like architecture, where the Python script acts as the “client” interacting with the “server” (SQLite database file).
- Database Initialization: Upon starting the application, it first connects to a SQLite database file (e.g.,
library.db). If the file doesn’t exist, SQLite creates it. It then ensures that the necessary tables (e.g.,books,borrowed_books) are created within this database. - User Interface (Console): The application presents a main menu to the user (librarian or library patron) via the console. This menu offers various options like adding a book, listing books, borrowing, returning, and searching.
- User Interaction: The user selects an option by entering a number. The Python script then prompts for relevant input (e.g., book title, author, ISBN, user name).
- Database Operations: Based on the user’s input and chosen action, the Python script executes SQL queries to perform operations on the SQLite database:
- INSERT: To add new books or record borrowing actions.
- SELECT: To retrieve lists of books or search for specific ones.
- UPDATE: To change a book’s quantity when borrowed or returned.
- DELETE: (Not implemented in this basic version, but can be added for removing books).
- Output Display: The results of database operations (e.g., a list of all books, search results, confirmation messages) are displayed back to the user on the console.
- Loop and Exit: The main menu loop continues until the user explicitly chooses to exit the application.
This direct interaction makes the system straightforward to understand and manage, ideal for a mini-project.
Read also: ImageViewerPro – Open Source macOS Image Viewer & Editor Built with SwiftUI
Screenshots / Demo Output
Since this is a console-based application, there are no graphical screenshots. The interaction will be purely text-based. Here’s what you can expect to see in your terminal:
Main Menu:
--- Library Management System --- 1. Add New Book 2. List All Books 3. Borrow Book 4. Return Book 5. Search Book 6. Exit Enter your choice:
Adding a Book:
Enter your choice: 1 Enter book title: The Hitchhiker's Guide to the Galaxy Enter author: Douglas Adams Enter ISBN (e.g., 978-0345391803): 978-0345391803 Enter quantity: 5 Book 'The Hitchhiker's Guide to the Galaxy' added successfully.
Listing All Books (with Tabulate for better formatting):
Enter your choice: 2 -------------------------------------------------------------------------------- | ID | Title | Author | ISBN | Quantity | Available | -------------------------------------------------------------------------------- | 1 | The Hitchhiker's Guide to the Galaxy | Douglas Adams | 978-0345391803 | 5 | Yes | | 2 | 1984 | George Orwell | 978-0451524935 | 3 | Yes | --------------------------------------------------------------------------------
Borrowing a Book:
Enter your choice: 3 Enter ISBN of the book to borrow: 978-0345391803 Enter your name (borrower): Alice Book 'The Hitchhiker's Guide to the Galaxy' borrowed by Alice. Remaining quantity: 4.
Returning a Book:
Enter your choice: 4 Enter ISBN of the book to return: 978-0345391803 Enter your name (borrower): Alice Book 'The Hitchhiker's Guide to the Galaxy' returned by Alice. Updated quantity: 5.
Searching for a Book:
Enter your choice: 5 Search by (1: Title, 2: Author, 3: ISBN): 1 Enter title to search: 1984 --------------------------------------------------------------- | ID | Title | Author | ISBN | Quantity | Available | --------------------------------------------------------------- | 2 | 1984 | George Orwell | 978-0451524935 | 3 | Yes | ---------------------------------------------------------------
Installation & Setup Guide
Follow these steps to get the Library Management System up and running on your local machine:
- Install Python 3.14+:If you don’t have Python installed, download the latest version from the official website: python.org/downloads. Make sure to check the option “Add Python to PATH” during installation.
- Verify Python Installation:Open your terminal or command prompt and type:
python --version # Expected output similar to: Python 3.14.0 - Create Project Directory:Create a new folder for your project:
mkdir library_management_system cd library_management_system - (Optional) Install Tabulate Library:For a nicer table display in the console, install the `tabulate` library. If you prefer to keep it minimal, you can skip this, and the code will use basic print statements for listing.
pip install tabulate - Create the Python Script:Inside the
library_management_systemfolder, create a new file namedlibrary_management.py(or any other name you prefer). Open this file in your IDE or text editor. - Copy the Source Code:Copy the complete Python source code provided in the next section and paste it into your
library_management.pyfile. - Run the Application:Save the file and run the script from your terminal within the project directory:
python library_management.pyThe application’s main menu will appear, and you can start interacting with it.
Read also: Welcome to the ToolNPlay Blog: Your New Hub for Tools, AI, and Games
Source Code Section
library_management.py
import sqlite3
from datetime import datetime
# Optional: Import tabulate for better table formatting.
# If you don't install it, the program will fall back to basic printing.
try:
from tabulate import tabulate
TABULATE_AVAILABLE = True
except ImportError:
TABULATE_AVAILABLE = False
print("Warning: 'tabulate' library not found. Listing books will use basic formatting.")
DATABASE_NAME = 'library.db'
def connect_db():
"""Establishes a connection to the SQLite database."""
conn = sqlite3.connect(DATABASE_NAME)
return conn
def create_tables():
"""Creates necessary tables in the database if they don't exist."""
conn = connect_db()
cursor = conn.cursor()
# Books table
cursor.execute('''
CREATE TABLE IF NOT EXISTS books (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
author TEXT NOT NULL,
isbn TEXT UNIQUE NOT NULL,
quantity INTEGER NOT NULL
)
''')
# Borrowed Books table
cursor.execute('''
CREATE TABLE IF NOT EXISTS borrowed_books (
borrow_id INTEGER PRIMARY KEY AUTOINCREMENT,
book_id INTEGER NOT NULL,
borrower_name TEXT NOT NULL,
borrow_date TEXT NOT NULL,
return_date TEXT,
FOREIGN KEY (book_id) REFERENCES books(id)
)
''')
conn.commit()
conn.close()
def add_book(title, author, isbn, quantity):
"""Adds a new book to the library."""
conn = connect_db()
cursor = conn.cursor()
try:
cursor.execute("INSERT INTO books (title, author, isbn, quantity) VALUES (?, ?, ?, ?)",
(title, author, isbn, quantity))
conn.commit()
print(f"Book '{title}' added successfully.")
except sqlite3.IntegrityError:
print(f"Error: A book with ISBN '{isbn}' already exists.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
conn.close()
def list_all_books():
"""Lists all books in the library."""
conn = connect_db()
cursor = conn.cursor()
cursor.execute("SELECT id, title, author, isbn, quantity FROM books")
books = cursor.fetchall()
conn.close()
if not books:
print("No books in the library.")
return
headers = ["ID", "Title", "Author", "ISBN", "Quantity", "Available"]
table_data = []
for book in books:
book_id, title, author, isbn, quantity = book
available_status = "Yes" if quantity > 0 else "No"
table_data.append([book_id, title, author, isbn, quantity, available_status])
if TABULATE_AVAILABLE:
print(tabulate(table_data, headers=headers, tablefmt="grid"))
else:
# Basic printing if tabulate is not available
print("-" * 80)
print(f"{'ID':<4} | {'Title':<30} | {'Author':<20} | {'ISBN':<15} | {'Qty':<5} | {'Available':<10}")
print("-" * 80)
for row in table_data:
print(f"{row:<4} | {row:<30} | {row:<20} | {row:<15} | {row:<5} | {row:<10}")
print("-" * 80)
def borrow_book(isbn, borrower_name):
"""Allows a user to borrow a book."""
conn = connect_db()
cursor = conn.cursor()
try:
cursor.execute("SELECT id, title, quantity FROM books WHERE isbn = ?", (isbn,))
book = cursor.fetchone()
if book:
book_id, title, quantity = book
if quantity > 0:
# Decrease book quantity
cursor.execute("UPDATE books SET quantity = ? WHERE id = ?", (quantity - 1, book_id))
# Record the borrowing
borrow_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cursor.execute("INSERT INTO borrowed_books (book_id, borrower_name, borrow_date) VALUES (?, ?, ?)",
(book_id, borrower_name, borrow_date))
conn.commit()
print(f"Book '{title}' borrowed by {borrower_name}. Remaining quantity: {quantity - 1}.")
else:
print(f"Book '{title}' is currently out of stock.")
else:
print(f"Book with ISBN '{isbn}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
conn.close()
def return_book(isbn, borrower_name):
"""Allows a user to return a borrowed book."""
conn = connect_db()
cursor = conn.cursor()
try:
cursor.execute("SELECT id, title FROM books WHERE isbn = ?", (isbn,))
book = cursor.fetchone()
if book:
book_id, title = book
# Find an outstanding borrow record for this book and borrower
cursor.execute("SELECT borrow_id FROM borrowed_books WHERE book_id = ? AND borrower_name = ? AND return_date IS NULL",
(book_id, borrower_name))
borrow_record = cursor.fetchone()
if borrow_record:
borrow_id = borrow_record
return_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Update the borrow record
cursor.execute("UPDATE borrowed_books SET return_date = ? WHERE borrow_id = ?",
(return_date, borrow_id))
# Increase book quantity
cursor.execute("UPDATE books SET quantity = quantity + 1 WHERE id = ?", (book_id,))
conn.commit()
# Get updated quantity for display
cursor.execute("SELECT quantity FROM books WHERE id = ?", (book_id,))
updated_quantity = cursor.fetchone()
print(f"Book '{title}' returned by {borrower_name}. Updated quantity: {updated_quantity}.")
else:
print(f"No outstanding borrow record found for book '{title}' by {borrower_name} or it was already returned.")
else:
print(f"Book with ISBN '{isbn}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
conn.close()
def search_book(query, search_by='title'):
"""Searches for books by title, author, or ISBN."""
conn = connect_db()
cursor = conn.cursor()
if search_by == 'title':
cursor.execute("SELECT id, title, author, isbn, quantity FROM books WHERE title LIKE ?", ('%' + query + '%',))
elif search_by == 'author':
cursor.execute("SELECT id, title, author, isbn, quantity FROM books WHERE author LIKE ?", ('%' + query + '%',))
elif search_by == 'isbn':
cursor.execute("SELECT id, title, author, isbn, quantity FROM books WHERE isbn LIKE ?", ('%' + query + '%',))
else:
print("Invalid search criteria.")
conn.close()
return
books = cursor.fetchall()
conn.close()
if not books:
print(f"No books found matching '{query}'.")
return
headers = ["ID", "Title", "Author", "ISBN", "Quantity", "Available"]
table_data = []
for book in books:
book_id, title, author, isbn, quantity = book
available_status = "Yes" if quantity > 0 else "No"
table_data.append([book_id, title, author, isbn, quantity, available_status])
if TABULATE_AVAILABLE:
print(tabulate(table_data, headers=headers, tablefmt="grid"))
else:
# Basic printing if tabulate is not available
print("-" * 80)
print(f"{'ID':<4} | {'Title':<30} | {'Author':<20} | {'ISBN':<15} | {'Qty':<5} | {'Available':<10}")
print("-" * 80)
for row in table_data:
print(f"{row:<4} | {row:<30} | {row:<20} | {row:<15} | {row:<5} | {row:<10}")
print("-" * 80)
def main_menu():
"""Displays the main menu and handles user choices."""
while True:
print("\n--- Library Management System ---")
print("1. Add New Book")
print("2. List All Books")
print("3. Borrow Book")
print("4. Return Book")
print("5. Search Book")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == '1':
title = input("Enter book title: ")
author = input("Enter author: ")
isbn = input("Enter ISBN (e.g., 978-0345391803): ")
try:
quantity = int(input("Enter quantity: "))
if quantity < 0:
print("Quantity cannot be negative.")
continue
add_book(title, author, isbn, quantity)
except ValueError:
print("Invalid quantity. Please enter a number.")
elif choice == '2':
list_all_books()
elif choice == '3':
isbn = input("Enter ISBN of the book to borrow: ")
borrower_name = input("Enter your name (borrower): ")
borrow_book(isbn, borrower_name)
elif choice == '4':
isbn = input("Enter ISBN of the book to return: ")
borrower_name = input("Enter your name (borrower): ") # Required to match specific outstanding borrow
return_book(isbn, borrower_name)
elif choice == '5':
search_choice = input("Search by (1: Title, 2: Author, 3: ISBN): ")
if search_choice == '1':
query = input("Enter title to search: ")
search_book(query, 'title')
elif search_choice == '2':
query = input("Enter author to search: ")
search_book(query, 'author')
elif search_choice == '3':
query = input("Enter ISBN to search: ")
search_book(query, 'isbn')
else:
print("Invalid search option.")
elif choice == '6':
print("Exiting Library Management System. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
create_tables() # Ensure tables exist on startup
main_menu()
Learning Outcomes / Benefits
By completing this Library Management System project, students will gain valuable skills and knowledge:
- Python Fundamentals: Reinforce understanding of Python syntax, functions, conditional statements, loops, and basic input/output operations.
- Database Management (SQLite): Learn how to connect to a SQLite database, create tables, and perform essential CRUD (Create, Read, Update) operations using SQL queries through Python’s
sqlite3module. - Error Handling: Implement
try-exceptblocks to gracefully handle potential errors, such as invalid input or database integrity issues. - Modular Programming: Understand how to break down a larger problem into smaller, manageable functions, improving code organization and readability.
- Command-Line Interface (CLI) Development: Gain experience in building interactive console applications, which is a foundational skill for many types of software.
- Data Persistence: Comprehend the concept of storing application data permanently in a database, allowing it to persist across multiple runs of the program.
- Problem-Solving: Develop logical thinking and problem-solving abilities by designing the system’s logic and implementing its features.
Future Scope / Improvements
This mini-project can be expanded significantly. Here are some ideas for future enhancements:
- User Authentication: Implement a login system for librarians and regular users, with different access levels.
- User Management: Add functionality to register new users, view user details, and track their borrowed books.
- Advanced Search & Filtering: Allow searching by publication year, genre, or combination of criteria. Add filters for available/borrowed books.
- Due Dates & Fines: Implement a system to track borrowing due dates and calculate fines for overdue books.
- Book Deletion/Update: Add options to remove books from the library or update their details (e.g., title, author).
- Reporting: Generate reports like “most popular books,” “overdue books list,” or “borrowing history for a user.”
- Graphical User Interface (GUI): Migrate from a console-based interface to a desktop application using libraries like Tkinter, PyQt, or Kivy.
- Web Interface: Develop a web-based application using frameworks like Flask or Django to make it accessible via a browser.
- External Data Integration: Fetch book details (like author, publication year) from online APIs using ISBN.
Conclusion
This Library Management System project provides a solid foundation for beginners to understand core programming concepts and database interaction using Python and SQLite. It’s a practical application that demonstrates how to manage data persistently and build an interactive command-line tool. By extending this project with the suggested improvements, you can further enhance your skills and explore more advanced topics in software development. Happy coding!
