I have just started to learn Python and I have a question regarding the FOR LOOP and how to make it loop until he finds a specific element in a list and then make it stop without iterating through the other list's elements :
I created two python file: 1) Database.py 2) App.py
In "Database.py" I have the following code:
books = []
In "App.py" I have this code:
def prompt_read_book():
book_to_search = input("Write the NAME of the book you want to mark as 'READ':\n")
for book in database.books:
if book_to_search.lower() == book["name"]:
print(f"The book '{book_to_search}' is now marked as READ")
book["read"] = True
print("-" * 40)
else:
print(f"Sorry but the book {book_to_search} is not in the database")
print("-" * 40)
When I have more than 1 book (2 or more) in my books
list, the function I wrote does not work as I expected.
Example:
books = [{"name": "Fight Club", "author": "Chuck Palahniuk", "read": False}, {"name": "Homo Deus", "author": "Yuval Noah Harari", "read": False}]
I want to "mark as READ" only the book with name "Fight Club".
So I input the name "Fight Club".
The book_to_search
variable becomes: Fight Club
The function runs correctly and changes the {"read": False}
to {"read": True}
HOWEVER
Since I am in the for loop, it keeps iterating and it also prints: "Sorry but the book Homo Deus is not in the database" (My understanding of the problem is the following: since we are in a for loop, the program checks one by one all the elements of the list to find if they match with the input the user wrote. Thus I need a way to stop the for loop once the matching element has been found).
What I would like is the following:
-Once the book_to_search
matches with the element of the dictionary, the for loop has to stop without iterating the others list' elements
-If the book_to_search
does to match with any element in the dictionary, I want to print "Sorry but the book {book_to_search} is not in the database"