KEMBAR78
Class Library | PDF | Chess Theory | Chess
0% found this document useful (0 votes)
79 views3 pages

Class Library

The document outlines a Library class that manages books and members, allowing functionalities such as adding books, borrowing, returning, displaying, and searching for books. It also includes methods to compute average books borrowed, find the most and least borrowed books, and show frequently borrowed books. A main function provides a menu-driven interface for user interaction with the library system.

Uploaded by

hannyjangir1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views3 pages

Class Library

The document outlines a Library class that manages books and members, allowing functionalities such as adding books, borrowing, returning, displaying, and searching for books. It also includes methods to compute average books borrowed, find the most and least borrowed books, and show frequently borrowed books. A main function provides a menu-driven interface for user interaction with the library system.

Uploaded by

hannyjangir1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

class Library:

def __init__(self):
self.books = {} # title -> {author, total, borrowed}
self.members = {} # member_id -> books borrowed

def add_book(self, title, author, total_copies):


if title in self.books:
print(f"'{title}' is already in the library.")
else:
self.books[title] = {
'author': author,
'total_copies': total_copies,
'borrowed': 0
}
print(f"Book '{title}' by {author} added to the library.")

def borrow_book(self, title, member_id):


if title not in self.books:
print(f"'{title}' is not available in the library.")
return

book = self.books[title]
available = book['total_copies'] - book['borrowed']

if available > 0:
book['borrowed'] += 1
self.members[member_id] = self.members.get(member_id, 0) + 1
print(f"'{title}' has been borrowed by member {member_id}. Enjoy
reading!")
else:
print(f"Sorry, all copies of '{title}' are currently borrowed.")

def return_book(self, title, member_id):


if title not in self.books:
print(f"'{title}' is not available in the library.")
return

book = self.books[title]
if book['borrowed'] > 0 and self.members.get(member_id, 0) > 0:
book['borrowed'] -= 1
self.members[member_id] -= 1
print(f"'{title}' has been returned. Thank you!")
else:
print(f"'{title}' was not borrowed or is already returned.")

def display_books(self):
print("\n--- Library Book Collection ---")
if not self.books:
print("No books in the library.")
return
for title, info in self.books.items():
available = info['total_copies'] - info['borrowed']
print(f"Title: {title}, Author: {info['author']}, Available Copies:
{available}/{info['total_copies']}")

def search_book(self, title):


print(f"\nSearching for '{title}'...")
if title in self.books:
info = self.books[title]
available = info['total_copies'] - info['borrowed']
print(f"Found! Title: {title}, Author: {info['author']}, Available
Copies: {available}/{info['total_copies']}")
else:
print(f"'{title}' not found in the library.")

def compute_avg_books_borrowed(self):
print("\n--- Average Books Borrowed ---")
if not self.members:
print("No members or borrowings yet.")
return
total_books_borrowed = sum(self.members.values())
num_members = len(self.members)
avg = total_books_borrowed / num_members
print(f"Average books borrowed by members: {avg:.2f}")

def find_highest_lowest_borrowed_books(self):
print("\n--- Most & Least Borrowed Books ---")
if not self.books:
print("No books in the library.")
return

highest = max(self.books.items(), key=lambda item: item[1]['borrowed'])


lowest = min(self.books.items(), key=lambda item: item[1]['borrowed'])

print(f"Most borrowed book: '{highest[0]}' ({highest[1]['borrowed']}


times)")
print(f"Least borrowed book: '{lowest[0]}' ({lowest[1]['borrowed']}
times)")

def most_frequently_borrowed_books(self):
print("\n--- Frequently Borrowed Books ---")
if not self.books:
print("No books in the library.")
return

sorted_books = sorted(self.books.items(), key=lambda item: item[1]


['borrowed'], reverse=True)
for title, info in sorted_books:
if info['borrowed'] > 0:
print(f"'{title}' borrowed {info['borrowed']} times")

def display_menu():
print("\n====== Library Management System ======")
print("1. Add a book")
print("2. Borrow a book")
print("3. Return a book")
print("4. Display all books")
print("5. Search for a book")
print("6. Compute average books borrowed")
print("7. Find highest and lowest borrowed books")
print("8. Show most frequently borrowed books")
print("0. Exit")

def main():
lib = Library()
while True:
display_menu()
choice = input("Enter your choice: ")

if choice == '1':
title = input("Enter book title: ")
author = input("Enter author: ")
total = int(input("Enter total copies: "))
lib.add_book(title, author, total)

elif choice == '2':


title = input("Enter book title to borrow: ")
member_id = input("Enter member ID: ")
lib.borrow_book(title, member_id)

elif choice == '3':


title = input("Enter book title to return: ")
member_id = input("Enter member ID: ")
lib.return_book(title, member_id)

elif choice == '4':


lib.display_books()

elif choice == '5':


title = input("Enter book title to search: ")
lib.search_book(title)

elif choice == '6':


lib.compute_avg_books_borrowed()

elif choice == '7':


lib.find_highest_lowest_borrowed_books()

elif choice == '8':


lib.most_frequently_borrowed_books()

elif choice == '0':


print("Thank you for using the Library Management System!")
break

else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
main()

You might also like