In this guide, you will learn to implement a simple library system using classes in Python. You will create a library management system to display books, add books, lend and return books.
Before we get started let’s understand what classes are. Classes, in general, enable a way to bunch data and functionality together. Each class has attributes that are unique to it. Attributes of one class can be inherited by other classes using the concept of inheritance or multiple inheritance. Classes can have methods for modifying their state. In Python, implementing classes does require a minimum knowledge of syntax and semantics.
Now that we have a basic grasp on the concept of classes, let’s try to create a simple library management system that will help you to display, add, lend and return books!
First, let’s import sys module into our program. This will supplement the functions, constants, variables, and methods of the Python interpreter. Let’s create a class called ‘Library’. We are using self. to access the attributes ad methods. It symbolizes the instance of the class. Please note that self is a parameter in function and it is advisable to use it because it improves the readability of the code.
import sys class Library: def __init__(self, listofbooks, lname): self.listofbooks = listofbooks self.lname = lname self.lenddata = {}
Next, lets write the code segment to display the list of books available. We are using the count() function in Python to return the count of a given element in a list. This method returns an integer value. Another method used is the enumerate() method which adds a counter to an iterable and gives back a enumerate object. This object can be applied in for loops or translated into tuples using the list() method.
# Display list of books def displaybooks(self): print(' \n Books which are available for use : ') for count, book in enumerate(self.listofbooks, 1): print(f'{count}. {book}')
Since we also need a way to add a book to the library, let’s figure out a code segment for it. First, let's define a function called ‘addbooks’. We are using the append() method to append or add an item to the end of the list. In this, it adds it to the ‘listofbooks’ which is referenced in self.
# Add new book to the list def addbooks(self, newbook): # Append the book in the list of books self.listofbooks.append(newbook) print(f'"{newbook}" is added to the list.\n')
The next function we need in the library system is to lend a book. To implement this, we are using the if-else statement in Python. This code first checks if the mentioned book is on the book list or not. And if it is, then it checks if the book is in the lend data or not. If the book has already been lent, it displays a ‘sorry’ message. Else, the book will be successfully lent. If the book is not on the list at all, it will send an error message.
# lend book from the list def lendbooks(self, lendername, lendingbook): # Checking the book is in book-list or not if lendingbook in self.listofbooks: # Checking the book is in lend data or not if lendingbook in self.lenddata: print(f'Sorry! This book is lend by {self.lenddata[lendingbook]}.\n') else: self.lenddata[lendingbook] = lendername print('Book has been successfully lend.') else: print('Sorry! you entered the wrong book name.')
the last function that a library system should allow is – returning the book. For this as well, we will use the logic of an if-else loop. If the book is already in the lending history/data, the system will ask if you want to return the book or not. if it is confirmed that the user wants to return a book, the following message will be displayed:
Thank you! Your book has been returned.
If no confirmation is received, then it is skipped. But if a book that is not in the lending data is returned, it will display the following message:
Sorry! You entered the wrong book name.
# Return lend book to the list def returnbooks(self, lendingbook): if lendingbook in self.lenddata: print(f'Lend details:\nThis book is lend by {self.lenddata[lendingbook]}.\n' f'If you want to return this book, enter "y" otherwise, press any key to skip.') r_input = input('Enter: ') if r_input == 'y': del self.lenddata[lendingbook] print('Thank you! Your book has been returned.\n') else: pass else: print('Sorry! you entered the wrong book name.')
Now, let’s create the main function and run an infinite loop asking the user for input. In the main body, we will define the library name, the functions which will help us add / return/lend/display books, etc. we will also a menu-drive display style that will ask for the input of the user. Since the function varies according to the user’s input, we are using if and elif structures. You can also try implementing the same using a switch case.
Since we finished all the functions of a library management system, let’s bunch the bits of code together and check the output.
import sys class Library: def __init__(self, listofbooks, lname): self.listofbooks = listofbooks self.lname = lname self.lenddata = {} # Display list of books def displaybooks(self): print(' \n Books which are available for use : ') for count, book in enumerate(self.listofbooks, 1): print(f'{count}. {book}') # Add new book to the list def addbooks(self, newbook): # Append the book in the list of books self.listofbooks.append(newbook) print(f'"{newbook}" is added to the list.\n') # lend book from the list def lendbooks(self, lendername, lendingbook): # Checking the book is in book-list or not if lendingbook in self.listofbooks: # Checking the book is in lend data or not if lendingbook in self.lenddata: print(f'Sorry! This book is lend by {self.lenddata[lendingbook]}.\n') else: self.lenddata[lendingbook] = lendername print('Book has been successfully lend.') else: print('Sorry! you entered the wrong book name.') # Return lend book to the list def returnbooks(self, lendingbook): if lendingbook in self.lenddata: print(f'Lend details:\nThis book is lend by {self.lenddata[lendingbook]}.\n' f'If you want to return this book, enter "y" otherwise, press any key to skip.') r_input = input('Enter: ') if r_input == 'y': del self.lenddata[lendingbook] print('Thank you! Your book has been returned.\n') else: pass else: print('Sorry! you entered the wrong book name.') def main(): # By deafault variables listofbooks = ["Data analytics for beginners'", "Coding can be fun!", "Wings of fire", "Behavioral neuroscience", "Introduction to Python", "class XII RD sharma"] lname = "Khyati's Library" lib = Library(listofbooks, lname) print(f'\n---------------- || Welcome to {lib.lname} ||-----------------\n') while True: print('\n\t\t\t || Main menu || ') print('1. To view the books available to you, please enter "p"\n2. To lend books to this library, please enter "l"\n' '3. To return books, Please enter "r"\n4. To add books to the library shelf, please enter "a"\n5. To quit or exit, please enter "x"') _input = input("Please Enter your input here: ") if _input == "x": print('\nThank you for using this system! Please visit us again :) ') sys.exit() elif _input == "p": lib.displaybooks() # Main menu or exit minput = input("For continuing with main menu enter 'c' or " "exit enter 'X'\nEnter: ") if minput == 'c': continue elif minput == 'x': print('\nThank you for using this system.') sys.exit() elif _input == "l": lname = input('Enter your name: ') lbook = input('Enter the name of the book you want to lend: ') lib.lendbooks(lname, lbook) # Main menu or exit minput = input("For continuing with main menu enter 'c' or " "exit enter 'x'\nEnter: ") if minput == 'c': continue elif minput == 'x': print('\nThank you for using this system. Please visit us again :)') sys.exit() elif _input == "r": rbook = input('Enter the book name which you want to return: ') lib.returnbooks(rbook) elif _input == "a": add = input('Add the book to the Book lists:\n') lib.addbooks(add) minput = input("For continuing with main menu enter 'c' or " "exit enter 'x'\nEnter: ") if minput == 'c': continue elif minput == 'x': print('\nThank you for using this system.') sys.exit() if __name__ == '__main__': main()
let's check the output!
OUTPUT: ---------------- || Welcome to Khyati's Library ||----------------- || Main menu || 1. To view the books available to you, please enter "p" 2. To lend books to this library, please enter "l" 3. To return books, Please enter "r" 4. To add books to the library shelf, please enter "a" 5. To quit or exit, please enter "x" Please Enter your input here: p Books which are available for use : 1. Data analytics for beginners' 2. Coding can be fun! 3. Wings of fire 4. Behavioral neuroscience 5. Introduction to Python 6. class XII RD sharma For continuing with main menu enter 'c' or exit enter 'X' Enter: c || Main menu || 1. To view the books available to you, please enter "p" 2. To lend books to this library, please enter "l" 3. To return books, Please enter "r" 4. To add books to the library shelf, please enter "a" 5. To quit or exit, please enter "x" Please Enter your input here: l Enter your name: abc Enter the name of the book you want to lend: abc Sorry! you entered the wrong book name. For continuing with main menu enter 'c' or exit enter 'x' Enter: c || Main menu || 1. To view the books available to you, please enter "p" 2. To lend books to this library, please enter "l" 3. To return books, Please enter "r" 4. To add books to the library shelf, please enter "a" 5. To quit or exit, please enter "x" Please Enter your input here: r Enter the book name which you want to return: wings of fire Sorry! you entered the wrong book name. || Main menu || 1. To view the books available to you, please enter "p" 2. To lend books to this library, please enter "l" 3. To return books, Please enter "r" 4. To add books to the library shelf, please enter "a" 5. To quit or exit, please enter "x" Please Enter your input here: a Add the book to the Book lists: The alchemist - Paulo cohelo "The alchemist - Paulo cohelo " is added to the list. For continuing with main menu enter 'c' or exit enter 'x' Enter: x Thank you for using this system.And there! We have implemented and learned about a simple library management system in Python.
Submitted by KHYATI MADDALI (khyatimaddali)
Download packets of source code on Coders Packet
Comments