0

I have a Class Library, inside which I have declared a method borrowBook(self, bookname). Whenever I call this method it successfully displays the name of the first book which is at index 0 in the list - availablebooks, but whenever I enter a bookname which is at index other than 0 then it becomes unable to find that book and prints the else part!

class Library:
.
.
.
def borrowBook(self, bookname):
        for book in range(len(availablebooks)):
            if bookname in availablebooks[book]['Title']:
                print("Here is your book! Enjoy")
                availablebooks.pop(book)
                return True
            else:
                print("The book is not available")
                return False
.
.
.
availablebooks = []
.
.
.
choice = int(input("Enter your choice (1/2/3): "))
if choice == 1:
    library.displayAvailableBooks()
elif choice == 2:
    library.borrowBook('Eloquent JavaScript, Third Edition')

The availablebooks list looks like this:

availablebooks = [{'Title': 'Eloquent JavaScript, Third Edition', 'Author': 'Marijn Haverbeke'}], [{'Title': 'Practical Modern JavaScript', 'Author': 'Nicolás Bevacqua'}]

The book name in the borrowBook is at the first index of the list and it displays the desired result, but...

elif choice == 2:
    library.borrowBook('Practical Modern JavaScript')

This book is at index 1 and this time instead it skips to the else part of the method where it says: "The book is not available"

Help me to solve this. I am stuck! Thank You!

  • Please read [ask] and [mre]. Do not use invalid syntax to redact the code, and make sure the code example can stand on its own. Instead of telling us "the availablebooks looks like: ...", actually hard-code that into the code. Instead of showing us menu logic (unless you think it is actually related to the problem), hard-code the action to take that causes the problem. With the given example, I cannot reproduce the problem: `availablebooks` isn't actually a list, but a tuple of lists, and the indexing is wrong. – Karl Knechtel Jun 10 '22 at 10:53
  • Anyway, the problem is that it is only possible to return once from a function. In the first iteration of the loop, `return False` prevents any other books from being considered. This is a common error and has nothing to do with writing classes. – Karl Knechtel Jun 10 '22 at 10:54
  • As an aside: please also [familiarize yourself with Python's loops properly](https://nedbatchelder.com/text/iter.html) – Karl Knechtel Jun 10 '22 at 10:57

0 Answers0