Skip to content
Python project #09Intermediate

Library Management System

Books, members, 14-day loans, late fines, borrowing limits, searches and overdue reports, with every rule enforced by custom exceptions.

Estimated time
~4 hours to build
Files
4 files · 388 lines
Technologies
Python 3, dataclasses, datetime, Custom exceptions

Introduction

A library system is a great way to practise modelling: books and members are objects, loans connect them, and business rules (limits, due dates, fines) decide what is allowed. Every rule lives in one place and is reported with a clear message.

Problem statement

Support commands to add books (id, title, author, year) and members, borrow and return books on given dates, pay fines, search by title or author, list books and members, and report overdue books for a date. Loans last 14 days and cost ₹5 per late day. A member may hold at most 3 books and can't borrow while owing more than ₹100. Duplicate ids, unknown ids, books already on loan and invalid dates must be rejected.

Objectives

  • Model entities with dataclasses and a service class
  • Raise a custom exception for rule violations
  • Use datetime.date and timedelta for due dates
  • Search and filter collections

Features

  • Books and members with unique ids
  • Borrow/return with automatic due dates and fines
  • Limits: 3 books per member, ₹100 fine threshold
  • Case-insensitive search by title or author
  • Overdue report for any date

Concepts demonstrated

  • Object modelling
  • Business rules
  • Custom exception classes
  • Date arithmetic

System architecture

Book and Member are dataclasses; Library owns them in dictionaries keyed by upper-case id and implements add_book, add_member, borrow and give_back. Each rule raises LibraryError with a specific message before any state changes. run parses one command and calls the library; main prints errors and a final summary.

Folder structure

TextProject tree
library-management/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

189 lines
Pythonmain.py
"""Library Management System: books, members, loans, due dates and fines.
Commands:
book <id> <title> | <author> | <year>
member <id> <name>
borrow <member-id> <book-id> <YYYY-MM-DD>
return <book-id> <YYYY-MM-DD>
pay <member-id> <amount>
search <text> title or author, case-insensitive
books | members | overdue <YYYY-MM-DD>
quit
Rules: 14-day loans, a fine of Rs 5 per late day, at most 3 books per member,
and no new loans while unpaid fines exceed Rs 100.
"""
import sys
from dataclasses import dataclass, field
from datetime import date, timedelta
LOAN_DAYS, FINE_PER_DAY, MAX_BOOKS, FINE_LIMIT = 14, 5, 3, 100
class LibraryError(Exception):
"""A rule of the library was broken; the message explains which."""
@dataclass
class Book:
id: str
title: str
author: str
year: int
borrower: str | None = None
due: date | None = None
@dataclass
class Member:
id: str
name: str
books: list[str] = field(default_factory=list)
fines: int = 0
def ask(prompt: str) -> str | None:
try:
line = input(prompt)
except EOFError:
print()
return None
if not sys.stdin.isatty():
print(line)
return line.strip()
def parse_date(text: str) -> date:
try:
return date.fromisoformat(text)
except ValueError:
raise LibraryError(f"'{text}' is not a date (use YYYY-MM-DD)") from None
class Library:
def __init__(self):
self.books: dict[str, Book] = {}
self.members: dict[str, Member] = {}
def book(self, book_id: str) -> Book:
try:
return self.books[book_id.upper()]
except KeyError:
raise LibraryError(f"no book with id {book_id}") from None
def member(self, member_id: str) -> Member:
try:
return self.members[member_id.upper()]
except KeyError:
raise LibraryError(f"no member with id {member_id}") from None
def add_book(self, book_id: str, details: str) -> Book:
parts = [p.strip() for p in details.split("|")]
if len(parts) != 3 or not parts[2].isdigit():
raise LibraryError("format: book <id> <title> | <author> | <year>")
if book_id.upper() in self.books:
raise LibraryError(f"book id {book_id} already exists")
book = Book(book_id.upper(), parts[0], parts[1], int(parts[2]))
self.books[book.id] = book
return book
def add_member(self, member_id: str, name: str) -> Member:
if member_id.upper() in self.members:
raise LibraryError(f"member id {member_id} already exists")
member = Member(member_id.upper(), name)
self.members[member.id] = member
return member
def borrow(self, member_id: str, book_id: str, on: date) -> Book:
member, book = self.member(member_id), self.book(book_id)
if book.borrower:
raise LibraryError(f"'{book.title}' is already borrowed (due {book.due:%d %b})")
if len(member.books) >= MAX_BOOKS:
raise LibraryError(f"{member.name} already has {MAX_BOOKS} books")
if member.fines > FINE_LIMIT:
raise LibraryError(f"{member.name} owes Rs {member.fines}; pay fines above Rs {FINE_LIMIT} first")
book.borrower, book.due = member.id, on + timedelta(days=LOAN_DAYS)
member.books.append(book.id)
return book
def give_back(self, book_id: str, on: date) -> tuple[Book, Member, int]:
book = self.book(book_id)
if not book.borrower:
raise LibraryError(f"'{book.title}' is not on loan")
member = self.members[book.borrower]
late = max((on - book.due).days, 0)
fine = late * FINE_PER_DAY
member.fines += fine
member.books.remove(book.id)
book.borrower = book.due = None
return book, member, fine
def run(lib: Library, line: str) -> None:
command, _, rest = line.partition(" ")
command, args = command.lower(), rest.split()
if command == "book":
book = lib.add_book(args[0], rest[len(args[0]):]) if args else lib.add_book("", "")
print(f"Added book {book.id}: {book.title} by {book.author} ({book.year})")
elif command == "member":
member = lib.add_member(args[0], " ".join(args[1:]))
print(f"Added member {member.id}: {member.name}")
elif command == "borrow":
book = lib.borrow(args[0], args[1], parse_date(args[2]))
print(f"{lib.members[book.borrower].name} borrowed '{book.title}', due {book.due:%d %b %Y}")
elif command == "return":
book, member, fine = lib.give_back(args[0], parse_date(args[1]))
extra = f", {fine // FINE_PER_DAY} day(s) late: fine Rs {fine}" if fine else ", on time"
print(f"{member.name} returned '{book.title}'{extra}")
elif command == "pay":
member = lib.member(args[0])
amount = min(int(args[1]), member.fines)
member.fines -= amount
print(f"{member.name} paid Rs {amount}; still owes Rs {member.fines}")
elif command == "search":
text = rest.lower()
found = [b for b in lib.books.values() if text in b.title.lower() or text in b.author.lower()]
for b in found:
status = f"on loan to {lib.members[b.borrower].name}" if b.borrower else "available"
print(f" {b.id:<5}{b.title:<32}{b.author:<20}{status}")
if not found:
print(f" No books match '{rest}'.")
elif command == "books":
for b in sorted(lib.books.values(), key=lambda b: b.id):
print(f" {b.id:<5}{b.title:<32}{'out' if b.borrower else 'in'}")
elif command == "members":
for m in lib.members.values():
print(f" {m.id:<5}{m.name:<10}books: {len(m.books)} fines: Rs {m.fines}")
elif command == "overdue":
on = parse_date(args[0])
late = [b for b in lib.books.values() if b.due and b.due < on]
for b in sorted(late, key=lambda b: b.due):
days = (on - b.due).days
print(f" {b.title:<32}{lib.members[b.borrower].name:<10}{days} days late, fine so far Rs {days * FINE_PER_DAY}")
if not late:
print(" Nothing is overdue.")
else:
raise LibraryError("unknown command")
def main() -> None:
lib = Library()
print("Library Management System")
while True:
line = ask("> ")
if line is None or line.lower() == "quit":
break
if not line:
continue
try:
run(lib, line)
except LibraryError as error:
print(f"Error: {error}")
except (IndexError, ValueError):
print("Error: missing or invalid arguments for that command")
on_loan = sum(1 for b in lib.books.values() if b.borrower)
print(f"{len(lib.books)} books ({on_loan} on loan), {len(lib.members)} members, fines due Rs {sum(m.fines for m in lib.members.values())}.")
if __name__ == "__main__":
main()

What each file does

main.py
The data classes, the Library service with all lending rules, and the command loop.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
Library Management System
> book B1 Python Crash Course | Eric Matthes | 2019
Added book B1: Python Crash Course by Eric Matthes (2019)
> book B2 Clean Code | Robert C. Martin | 2008
Added book B2: Clean Code by Robert C. Martin (2008)
> book B3 Fluent Python | Luciano Ramalho | 2022
Added book B3: Fluent Python by Luciano Ramalho (2022)
> book B4 The Pragmatic Programmer | Hunt and Thomas | 1999
Added book B4: The Pragmatic Programmer by Hunt and Thomas (1999)
> book B5 Automate the Boring Stuff | Al Sweigart | 2019
Added book B5: Automate the Boring Stuff by Al Sweigart (2019)
> book B1 Duplicate | Nobody | 2000
Error: book id B1 already exists
> book B6 No Year | Someone
Error: format: book <id> <title> | <author> | <year>
> member M1 Asha
Added member M1: Asha
> member M2 Ravi
Added member M2: Ravi
> borrow M1 B1 2026-11-01
Asha borrowed 'Python Crash Course', due 15 Nov 2026
> borrow M1 B2 2026-11-01
Asha borrowed 'Clean Code', due 15 Nov 2026
> borrow M2 B1 2026-11-02
Error: 'Python Crash Course' is already borrowed (due 15 Nov)
> borrow M1 B3 2026-11-03
Asha borrowed 'Fluent Python', due 17 Nov 2026
> borrow M1 B4 2026-11-03
Error: Asha already has 3 books
> borrow M3 B4 2026-11-03
Error: no member with id M3
> search python
B1 Python Crash Course Eric Matthes on loan to Asha
B3 Fluent Python Luciano Ramalho on loan to Asha
> overdue 2026-11-20
Python Crash Course Asha 5 days late, fine so far Rs 25
Clean Code Asha 5 days late, fine so far Rs 25
Fluent Python Asha 3 days late, fine so far Rs 15
> return B1 2026-11-25
Asha returned 'Python Crash Course', 10 day(s) late: fine Rs 50
> return B2 2026-11-10
Asha returned 'Clean Code', on time
> return B5 2026-11-10
Error: 'Automate the Boring Stuff' is not on loan
> borrow M2 B1 2026-11-26
Ravi borrowed 'Python Crash Course', due 10 Dec 2026
> return B3 2026-12-20
Asha returned 'Fluent Python', 33 day(s) late: fine Rs 165
> members
M1 Asha books: 0 fines: Rs 215
M2 Ravi books: 1 fines: Rs 0
> borrow M1 B5 2026-12-21
Error: Asha owes Rs 215; pay fines above Rs 100 first
> pay M1 80
Asha paid Rs 80; still owes Rs 135
> borrow M1 B5 2026-12-21
Error: Asha owes Rs 135; pay fines above Rs 100 first
> books
B1 Python Crash Course out
B2 Clean Code in
B3 Fluent Python in
B4 The Pragmatic Programmer in
B5 Automate the Boring Stuff in
> quit
5 books (1 on loan), 2 members, fines due Rs 135.
Input
book B1 Python Crash Course | Eric Matthes | 2019
book B2 Clean Code | Robert C. Martin | 2008
book B3 Fluent Python | Luciano Ramalho | 2022
book B4 The Pragmatic Programmer | Hunt and Thomas | 1999
book B5 Automate the Boring Stuff | Al Sweigart | 2019
book B1 Duplicate | Nobody | 2000
book B6 No Year | Someone
member M1 Asha
member M2 Ravi
borrow M1 B1 2026-11-01
borrow M1 B2 2026-11-01
borrow M2 B1 2026-11-02
borrow M1 B3 2026-11-03
borrow M1 B4 2026-11-03
borrow M3 B4 2026-11-03
search python
overdue 2026-11-20
return B1 2026-11-25
return B2 2026-11-10
return B5 2026-11-10
borrow M2 B1 2026-11-26
return B3 2026-12-20
members
borrow M1 B5 2026-12-21
pay M1 80
borrow M1 B5 2026-12-21
books
quit

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/expected-output.txt.
  • A duplicate book id and a book without a year are rejected.
  • Asha's fourth book is refused because of the 3-book limit, and an unknown member M3 is reported.
  • Returning Fluent Python 33 days late adds ₹165, so Asha (owing ₹215, then ₹135) can't borrow again.

Common errors

A failed borrow still changes the book's state

Check every rule first and only then update the book and member, as borrow() does.

KeyError for an unknown id

Translate it into LibraryError with a friendly message inside book() and member().

Possible improvements

  • Save the library to JSON
  • Support reservations when a book is on loan
  • Add multiple copies of the same title

Additional challenges

  1. 1Add a 'history <member>' command listing past loans.
  2. 2Waive fines for the first late day.
  3. 3Email-style reminders listing books due within two days.

Built and tested it yourself? Mark it to update your dashboard.