The Library Management System project is a Python-based application that simulates a basic library system. This project provides a hands-on opportunity to understand and apply fundamental Object-Oriented Programming (OOP) concepts in Python. Lets see how to code it


class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author
        self.available = True

    def borrow(self):
        if self.available:
            self.available = False
            return f"You have borrowed '{self.title}' by {self.author}."
        else:
            return f"'{self.title}' is currently unavailable."

    def return_book(self):
        self.available = True
        return f"You have returned '{self.title}'."

    def __str__(self):
        return f"'{self.title}' by {self.author}"


class User:
    def __init__(self, name):
        self.name = name
        self.borrowed_books = []

    def borrow_book(self, book):
        if book.available:
            self.borrowed_books.append(book)
            return f"{self.name} has borrowed '{book.title}'."
        else:
            return f"'{book.title}' is currently unavailable."

    def return_book(self, book):
        if book in self.borrowed_books:
            self.borrowed_books.remove(book)
            book.return_book()
            return f"{self.name} has returned '{book.title}'."
        else:
            return f"'{book.title}' was not borrowed by {self.name}."

    def __str__(self):
        return self.name


class Library:
    def __init__(self):
        self.books = []
        self.users = []

    def add_book(self, book):
        self.books.append(book)

    def add_user(self, user):
        self.users.append(user)

    def show_available_books(self):
        available_books = [book for book in self.books if book.available]
        if available_books:
            return "\n".join(str(book) for book in available_books)
        else:
            return "No books available in the library."

    def __str__(self):
        return "Library Management System"


# Create books
book1 = Book("Python Crash Course", "Eric Matthes")
book2 = Book("Clean Code", "Robert C. Martin")
book3 = Book("The Alchemist", "Paulo Coelho")

# Create users
user1 = User("Alice")
user2 = User("Bob")

# Create a library
library = Library()

# Add books and users to the library
library.add_book(book1)
library.add_book(book2)
library.add_user(user1)
library.add_user(user2)

# Demonstrate borrowing and returning books
print(user1.borrow_book(book1))
print(user2.borrow_book(book2))
print(user1.return_book(book2))
print(user2.borrow_book(book1))
print(user1.return_book(book3))

# Display available books
print("\nAvailable Books:")
print(library.show_available_books())

Day 16 : Project Library Management System

Day 16 : How to use Object-Oriented Programming in Python?

One Response

Leave a Reply

Your email address will not be published. Required fields are marked *