Assignment Overview
In this assignment, you will build a complete Library Management System that tracks books, library members, and borrowing records. This comprehensive project requires you to apply ALL concepts from Module 4: lists (4.1), tuples (4.2), slicing and indexing (4.3), and unpacking (4.4).
Lists (4.1)
Creating, modifying, sorting, and methods
Tuples (4.2)
Immutable data, namedtuples, returns
Slicing (4.3)
Extracting, reversing, stepping
Unpacking (4.4)
Star expressions, loop unpacking
The Scenario
City Central Library
You have been hired as a Python Developer at City Central Library, which needs a digital system to replace their paper-based records. The head librarian has given you this task:
"We need a Python system to track our 50+ books, 30+ members, and all borrowing transactions. The system should help us find overdue books, track popular genres, manage member accounts, and generate reports. Can you build this using only Python's built-in data structures?"
Your Task
Create a Python script called library_system.py that implements a complete library
management system. Your code must use lists, tuples, dictionaries, sets, slicing, and unpacking
to manage all library operations efficiently.
Initial Data
Your system starts with these pre-defined data structures. Important: Use these exact structures as your starting point:
Books Collection (List of Tuples)
# Each book: (book_id, title, author, genre, year, copies_total, copies_available)
books = [
("B001", "Python Crash Course", "Eric Matthes", "Programming", 2019, 3, 3),
("B002", "Clean Code", "Robert Martin", "Programming", 2008, 2, 1),
("B003", "The Pragmatic Programmer", "Hunt & Thomas", "Programming", 1999, 2, 2),
("B004", "To Kill a Mockingbird", "Harper Lee", "Fiction", 1960, 4, 3),
("B005", "1984", "George Orwell", "Fiction", 1949, 3, 2),
("B006", "Sapiens", "Yuval Harari", "History", 2011, 2, 1),
("B007", "Educated", "Tara Westover", "Biography", 2018, 3, 3),
("B008", "Atomic Habits", "James Clear", "Self-Help", 2018, 4, 2),
("B009", "Deep Work", "Cal Newport", "Self-Help", 2016, 2, 2),
("B010", "The Alchemist", "Paulo Coelho", "Fiction", 1988, 3, 1),
]
# Additional books for testing (add at least 5 more yourself)
# ("B011", "Book Title", "Author", "Genre", year, total_copies, available_copies)
Library Members (List of Dictionaries)
# Each member: dictionary with member details
members = [
{"member_id": "M001", "name": "Alice Johnson", "email": "alice@email.com", "join_year": 2020, "books_borrowed": []},
{"member_id": "M002", "name": "Bob Smith", "email": "bob@email.com", "join_year": 2021, "books_borrowed": []},
{"member_id": "M003", "name": "Carol White", "email": "carol@email.com", "join_year": 2019, "books_borrowed": []},
{"member_id": "M004", "name": "David Brown", "email": "david@email.com", "join_year": 2022, "books_borrowed": []},
{"member_id": "M005", "name": "Eve Davis", "email": "eve@email.com", "join_year": 2023, "books_borrowed": []},
]
# Add at least 3 more members yourself
Borrowing Records (List of Tuples)
# Each record: (record_id, member_id, book_id, borrow_date, due_date, return_date)
# return_date is None if not yet returned
borrowing_records = [
("R001", "M001", "B002", "2024-01-10", "2024-01-24", "2024-01-20"),
("R002", "M002", "B005", "2024-01-15", "2024-01-29", None), # Not returned yet
("R003", "M003", "B008", "2024-01-12", "2024-01-26", None), # Not returned yet
("R004", "M001", "B010", "2024-01-18", "2024-02-01", None), # Not returned yet
]
# Your functions will add more records as books are borrowed
Requirements
Your library_system.py must implement ALL of the following 15 functions.
Each function demonstrates specific Module 4 concepts.
Display All Books (List Iteration & Unpacking)
Function: display_books(books)
Must use: Tuple unpacking in loop
- Loop through books list
- Unpack each tuple:
book_id, title, author, genre, year, total, available = book - Print formatted book details (ID, title, author, available/total copies)
def display_books(books):
"""Display all books with unpacking."""
for book_id, title, author, genre, year, total, available in books:
print(f"{book_id}: {title} by {author} - {available}/{total} available")
# Must use tuple unpacking in the loop
Find Book by ID (List Search & Unpacking)
Function: find_book(books, book_id)
Must use: Loop with unpacking, return tuple
- Search for book matching the given book_id
- Return the entire book tuple if found
- Return None if not found
def find_book(books, book_id):
"""Find and return book tuple by ID."""
for book in books:
bid, title, author, genre, year, total, available = book
if bid == book_id:
return book
return None
Search Books by Genre (List Comprehension)
Function: get_books_by_genre(books, genre)
Must use: List comprehension with unpacking
- Filter books matching the given genre (case-insensitive)
- Return list of tuples:
(book_id, title, author) - Use list comprehension for filtering
def get_books_by_genre(books, genre):
"""Return list of (id, title, author) tuples for matching genre."""
# Must use list comprehension with tuple unpacking
return [(bid, title, author) for bid, title, author, g, *_ in books
if g.lower() == genre.lower()]
Get Unique Genres (Set from List)
Function: get_unique_genres(books)
Must use: Set comprehension or set constructor
- Extract all unique genres from books
- Return a sorted list of unique genres
def get_unique_genres(books):
"""Return sorted list of unique genres using set."""
genres = {genre for _, _, _, genre, *_ in books}
return sorted(genres)
Get Available Books (Slicing & Filtering)
Function: get_available_books(books)
Must use: List comprehension, check availability
- Filter books where copies_available > 0
- Return list of available book tuples
def get_available_books(books):
"""Return list of books that have copies available."""
return [book for book in books if book[-1] > 0] # Check last element (available)
Add New Member (Dictionary & List)
Function: add_member(members, member_id, name, email, join_year)
Must use: Dictionary creation, list append
- Create a new member dictionary with given details
- Initialize books_borrowed as empty list
- Append to members list
- Return True if added, False if member_id already exists
Find Member by ID (Dictionary Search)
Function: find_member(members, member_id)
Must use: Loop through list of dictionaries
- Search for member with matching member_id
- Return member dictionary if found, None otherwise
Borrow Book (List/Dict Modification)
Function: borrow_book(books, members, records, member_id, book_id, borrow_date, due_date)
Must use: List operations, dictionary update
- Check if member exists and book is available
- Decrease book's available copies (requires replacing tuple in list!)
- Add book_id to member's books_borrowed list
- Create new borrowing record tuple and add to records
- Return (True, "Success message") or (False, "Error message")
def borrow_book(books, members, records, member_id, book_id, borrow_date, due_date):
"""Process book borrowing - modify data structures appropriately."""
# 1. Find member and book
# 2. Check availability
# 3. Update book tuple (create new tuple with decreased available count)
# 4. Update member's books_borrowed list
# 5. Add record tuple to records
# Return tuple: (success_boolean, message_string)
Return Book (List/Dict Modification)
Function: return_book(books, members, records, member_id, book_id, return_date)
Must use: List operations, tuple replacement
- Find the borrowing record (where return_date is None)
- Update record with return_date (replace tuple)
- Increase book's available copies
- Remove book_id from member's books_borrowed
- Return (True, "Success") or (False, "Error")
Get Overdue Books (Filtering with Unpacking)
Function: get_overdue_books(records, current_date)
Must use: List comprehension with unpacking
- Filter records where return_date is None and due_date < current_date
- Return list of tuples:
(record_id, member_id, book_id, due_date) - Use tuple unpacking in comprehension
Get Books Borrowed by Member (Dictionary Access)
Function: get_member_books(members, books, member_id)
Must use: Dictionary operations, list filtering
- Find member's books_borrowed list
- Return list of book titles (look up each book_id)
Get Most Popular Genre (Dictionary/Set Operations)
Function: get_popular_genre(records, books)
Must use: Dictionary for counting, unpacking
- Count how many times books from each genre were borrowed
- Use dictionary to track genre: count
- Return tuple:
(genre_name, borrow_count)
Get Recent Books (Slicing)
Function: get_recent_books(books, n=5)
Must use: Sorting and slicing
- Sort books by publication year (descending)
- Return top N most recent books using slice
- Use sorted() with lambda key
def get_recent_books(books, n=5):
"""Return n most recent books using sorting and slicing."""
sorted_books = sorted(books, key=lambda b: b[4], reverse=True) # Sort by year
return sorted_books[:n] # Slice first n
Generate Library Report (String Formatting)
Function: generate_report(books, members, records)
Must use: All data structures, unpacking, len()
- Print total books, total members, total borrowed currently
- Print all unique genres
- Print top 3 most recent books
- Print members with currently borrowed books
Main Program (Integration)
Function: main()
Must use: All previous functions
- Initialize the three data structures with sample data
- Demonstrate at least 3 book borrowings
- Demonstrate at least 1 book return
- Display library report
- Show overdue books (if any)
- Use
if __name__ == "__main__":pattern
def main():
# Initialize data
books = [...] # Your book data
members = [...] # Your member data
borrowing_records = [] # Start empty
# Demo operations
print("=== Library Management System ===\n")
# Display all books
display_books(books)
# Borrow some books
borrow_book(books, members, borrowing_records, "M001", "B002", "2024-01-20", "2024-02-03")
# ... more operations
# Generate report
generate_report(books, members, borrowing_records)
if __name__ == "__main__":
main()
Submission
Create a public GitHub repository with the exact name shown below:
Required Repository Name
library-management-python
Required Files
library-management-python/
├── library_system.py # Your main Python script with ALL 15 functions
├── README.md # REQUIRED - see contents below
└── sample_output.txt # Copy of your program's console output
README.md Must Include:
- Your full name and submission date
- Brief description of your approach to each major function
- Explanation of how you handled modifying tuples (since they're immutable)
- Any challenges faced and how you solved them
- Instructions to run your script
- Sample output showing 3 borrowing transactions
Do Include
- All 15 functions implemented and working
- Docstrings for every function
- Comments explaining complex logic
- At least 15 books in initial dataset
- At least 8 members in initial dataset
- Demonstration of all major operations in main()
- README.md with all required sections
Do Not Include
- Any external libraries (csv, json, etc.)
- Any .pyc or __pycache__ files (use .gitignore)
- Hardcoded outputs (program must be dynamic)
- Code that doesn't run without errors
- Functions that don't use required concepts
Enter your GitHub username - we'll verify your repository automatically
Grading Rubric
Your assignment will be graded on the following criteria:
| Criteria | Points | Description |
|---|---|---|
| Lists Operations (4.1) | 30 | Correct use of lists, append, remove, comprehensions, and iteration |
| Tuples & Immutability (4.2) | 25 | Proper use of tuples for book data, handling tuple replacement correctly |
| Dictionaries & Sets | 20 | Correct dictionary operations for members, set for unique genres |
| Slicing & Indexing (4.3) | 15 | Proper use of slicing, negative indexing, and step values |
| Unpacking Patterns (4.4) | 25 | Tuple unpacking in loops, star expressions, multiple assignment |
| Functions (15 required) | 20 | All 15 functions implemented with correct logic and return values |
| Code Quality | 15 | Docstrings, comments, naming conventions, clean organization |
| Total | 150 |
Ready to Submit?
Make sure you have completed all requirements and reviewed the grading rubric above.
Submit Your AssignmentWhat You Will Practice
Lists Mastery (4.1)
Creating, modifying, appending, removing, list comprehensions, and nested lists for managing collections
Tuples & Immutability (4.2)
Using tuples for fixed data, handling immutability by creating new tuples, returning multiple values
Slicing & Indexing (4.3)
Extracting elements with slicing, negative indexing, step values, reversing sequences
Unpacking Patterns (4.4)
Tuple unpacking in loops, star expressions (*args), multiple assignment, swapping values
Pro Tips
Working with Tuples
- Remember: tuples are immutable!
- To "modify" a tuple, create a new one
- Use tuple unpacking to extract values easily
- Replace tuple in list:
books[index] = new_tuple
Unpacking Best Practices
- Use star (*) for "rest of values"
- Unpack in loops for cleaner code
- Use underscore (_) for ignored values
- Return tuples from functions for multiple values
Time Management
- Start with data structure definitions
- Build simple functions first (display, find)
- Test each function before moving to next
- Leave time for integration in main()
Common Mistakes
- Trying to modify tuples directly
- Not using unpacking when you should
- Forgetting to update all related data structures
- Not checking if item exists before accessing