Hello Friends
Creating library object.
I have a library.txt that contain 20 books and every line in library,txt contain author ,title and loan , my questions is how to create class and object for library script with python.
1. search at title
2. search at author
3. Borrow a book
4. Return a book.
5. Adds a new book.
6. Removes a book.
For example when someone borrowed a book we get ”The book is borrowed”
I shall be very grateful for your help.

class Library:

    def __init__(self, author, title):
        self.author = author
        self.title = title
        self.borrowed = False


def search_title:

def search_author:

def borrow_book:

def Return_book:

def add_book:

def remove_book:


-------- Main Program --------

print("Welcome to the library!")

I would think little if Library can be borrowed.

Hi sir
We can change the class name to Book and object to library.

Library can not be instance of Book either, but list of Book instances would be one abstraction of library.

Ok sir thanks.
Anyone can write this code so that I can understan it? please.

That person is you. We help you to debug if you get stuck.

Ok I will try but I would like know if Im thinking correct or wrong with my class and function?
I will appreciate som tips.!

You would have global variable holding the books in list, you do not need declare it global if you only alter it's elements. You just put

  mylibrary = []

in beginning of main routine outside functions.

Take couple of your books and play library with them as test case. You must consider carefully how you identify book. Luckily there is one global system available, but do not forget that library has some books many copies.

library.txt

Thanks Sir,
I would like to understand why should I create list myLibrary = [ ] and I have aleady library.txt.with all Books?

Sorry, but that comment does not make any kind of sense. That looks like text file on the disc for me.

Hi
I will be very grateful if some one tell my Im doing right.

class Catalog:
    # firstI have an empty list
    myLibrary = []
    #second I add som books to the list
    myLibrary.append(Catalog("Starting Out with Python", "Tony Gaddis")
    myLibrary.append(Catalog("Hello World Computer Programming for Kids and Other Beginners", "Carter Sand")
    myLibrary.append(Catalog("learning python", "Mark Lutz")





    def __init__(self, title, author):
        self.title = title
        self.author = author


    def add_book(self):
        #user add books
        addBook = input("Which book you like to add to LbraryList")

        for i in myLibrary:
            myLibrary.append(name)

    #user rmove books
    def remove_books(self):

        removeBook =  input("Which book you like to remove from LibraryList")
                 if removeBook in myLibrary:
                     myLibrar.remove(removeBook)

                  else:
                     print(removeBook,"not found in LibraryList")







library = Catalog()
library.add_book()
library.remove_books()

print(library)

myLibrary

You need not use append to empty list, just give it as normal list.

remove_books

is rubbish.

add_book

there is not MyLibrary object defined in function

init

What is meaning of title and author of Catalog?

library = Catalog()

This can not execute as initializer of Catalog needs parameters.

Maybe you can think your program as this: a class Library in which you hold objects books and some kind of connection (talking about the loan part) with the customers. This connection will be for the loan part, as each object book can be loan or is loaned. Each book object would have an author and a title.

I would advise you to put in your library class a list variable in which you will be storing the book elements, or a dictionary.

For getting elements from your .txt file, you'll need to make some researches of how you can split/divide a line into title, loan, authors etc.

Having that knowledge let me exaplin a bit how I see your program:
1st level: domain part. Here you have the lowest elements that compose your program. Here you'd have the Book class.
2nd level: repository part. Here you'll be storing elements into your repository/Library class. You can add here other functions for sorting and printing out elements.
3rd level: controller part. Here you try to validate parts of your code, try to "convert" the information given from the 4th level, ui level, into repository information.
4th level: ui part. Here you make a small/large (depending on your needs) console/GUI interface, from which you insert information into your application, information that will be processed by the controller part and then send to the repository part.

Here's an example of how you can read from a file, to get you started a bit.

    def _loadfromfile(self):
        fh = open(self.filename)
        for line in fh:
            fields = line.split(", ")
            bk=Book(fields[0], fields[1])
            self.book[bk.getBookId()] = bk
        fh.close()

where filename is the given file in which you have your books.
self.book is a dictionary in which you store your books, having as key of the dictionary a unique id, and as element the actual Book object.

Thank you very much Sir.
Now Im try to create an empty list like myLibrary = [] and append all books to list.
But my question is shout I have myLibrary = [] as a global variable? can I define it inside constuctor? if you give a little example just how can I think?

class Catalog:

    def __init__(self, author, title):
        self.author = author
        self.title = title
        self.borrowed = False
        self.myLibrary = []

    def add_book(self, book):

borrowed would indeed be one of the instance variables, but not of Catalog instances, but Book instance for each copy of book (possibly with same title in case of real library, not personal books).

The design given by Lucaci is correct and fine, but if I understand right, beyond your current level. That is design for real library system which you could use in real library (first lines makes the code compatible with Python2 as I use print with () and only one argument)

OK, to get you started, I give you back the code you posted fixed. It is far from finished, and I hope you can catch the meaning from there and go on implementing your full program. Usually adding reasonable fail safes for user input and other error handling at least doubles the code.

try:
    input, range = raw_input, xrange
except:
    pass

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

    def __str__(self):
        return "%r by %s" % (self.title, self.author)

class Catalog(object):
    #add some books to the list
    mylibrary = [Book("Starting Out with Python", "Tony Gaddis"),
                 Book("Hello World Computer Programming for Kids and Other Beginners", "Carter Sand"),
                 Book("learning python", "Mark Lutz")
                ]

    def __str__(self):
        return '\nBooks:\n\t' + '\n\t'.join("%i: %s" % (n, book) for n, book in enumerate(self.mylibrary))

    def add_book(self):
        self.mylibrary.append(Book(input("Which book you like to add to LibraryList:\nTitle: "),
                                   input("Author: ")))

    def remove_book(self):
        print(self)
        book =  int(input("Which book you like to remove from LibraryList? "))
        confirm = input("Removing book %i: %s from library, y/N? " % (book, self.mylibrary[book]))
        if confirm.lower() == 'y':
            del self.mylibrary[book]


library = Catalog()
library.add_book()
library.remove_book()

print(library)
"""Output:
Which book you like to add to LibraryList:
Title: Python
Author: Guido

Books:
    0: 'Starting Out with Python' by Tony Gaddis
    1: 'Hello World Computer Programming for Kids and Other Beginners' by Carter Sand
    2: 'learning python' by Mark Lutz
    3: 'Python' by Guido
Which book you like to remove from LibraryList? 2
Removing book 2: 'learning python' by Mark Lutz from library, y/N? y

Books:
    0: 'Starting Out with Python' by Tony Gaddis
    1: 'Hello World Computer Programming for Kids and Other Beginners' by Carter Sand
    2: 'Python' by Guido
"""

Thank you very much Tony,you are wonderful.(Tack så mycket)

(Tack ska du ha,) But consider that Book class would not in reality be real instance of book, but you would have a copy id for each copy and class which link to their book info (for same title same Book instance) etc. Maybe you should name Book instead BookInfo and add one BookCopy class for copies of books. If you want to use list indexes as id numbers, you should not del titles to remove but replace them with None.

Thank you Tony ,what about borrowed books(låna en bok)?can you give me idea?
Is it right?

def borrow_book(self):
print(self)
book = int(input("Which book you like to borrow it? "))
confirm = input("borrow book %i: %s from library, y/N? " % (book,  self.mylibrary[book]))
if confirm.lower() == 'y':

    self.borrowed = True

No, indention is off, the borrowed status would be in self.mylibrary[book].borrowed, not self.borrowed. You would need to change the __str__ method of collection only include not borrowed books.

Tack Tony du är underbar..

I try to search book in myLibrary but I dont know why looping continue?

def search_book(self):
    searchBook = input("Which book are you looking for? ")
        print(self)
        for book in self.myLibrary:
            if searchBook == book.title:

                print(book.title, "Book is found")
                break

            else:
                print(book.title,"Not found")

get out the loop the printing part, the else part, because every time the element searched is not found it will print that the elemenet was not found, thus on a larger scale, will fill up the screen with the "Not found" message.

def search_book(self):
    found=false
    searchBook = input("Which book are you looking for? ")
    for book in self.myLibrary:
        if (searchBook == book.title):
            found=true
            break
    if (found==true):
        print(searchBook,"\nFound it")
    else: print("We couldn't find it.")

Also use the correct indentation, and the correct syntax: the if statemen has to have it's condition enclosed in open brackets ().

Thank you Lucaci,thank you very much, now Im understand my misstake.

Correct advice, Lucaci, but found flag is unnecessary.

def search_book(self):
    searchBook = input("Which book are you looking for? ")
    for book in self.myLibrary:
        if (searchBook == book.title):
            print(book,"found")
            return
    print("We couldn't find it.")

I know, but again, in many of my explanations I put some things in order for others (who usually are the OP's) to understand better their mistakes, or the errors from their codes. But I think this won't catch on others.:)
P.S. Think about the satisfaction when they figure out that some things can be done simpler, with lesser code.

Thank you so much Tony.(Du är data Nörd)

What about borrow book?I don't know if my code is logic mybe there is bettter way(code) to do it?I will be thankful for help.

def borrow_book(self, borrowBook):
    borrowedBook =input("which you like to borrow it ?)
    for book in self.myLibrary:
        if(borrowBook in book.title and book.borrowed == False):
                        book.borrowed == True
                        print("You borrowed", book.title)
                        return


        print(book.title,"is already is borrowed")

#---main program---#

library = Catalog

borrowingBook = library.borrow_book(borrowedBook)                        

Missing quote at line 2. library is not instance of class but class itself.

Thanks.
When I run my code still print
you borrwed python.
we couldn't find it
python is already borrowed

When I borrow book It just print"you borrwed python"
And How can I put indicate beside book when its borrowed I mean when the user show all list
it will seem that the book python is borrowed.
Starting Out with Python,Tony Gaddis,borrwed.

def borrow_book(self, borrowBook):
    borrowedBook =input("which you like to borrow it ?")
    for book in self.myLibrary:
        if(borrowBook in book.title and book.borrowed == False):
                        book.borrowed == True
                        print("You borrowed", book.title)
        else:
                        print("We couldn't find it.")


                        return


        print(book.title,"is already borrowed")

#---main program---#

library = Catalog()

borrowingBook = library.borrow_book(borrowedBook)                        

My be Im thinking wrong!!!

book.borrowed == True

This is conditional expression, but the result is not used.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.