Python 如何在找到字典(包含在列表中)中的元素后停止列表中的for循环

Python 如何在找到字典(包含在列表中)中的元素后停止列表中的for循环,python,Python,我刚刚开始学习Python,我有一个关于FOR循环的问题,以及如何使其循环,直到他在列表中找到一个特定元素,然后在不迭代其他列表元素的情况下使其停止: 我创建了两个python文件:1 Database.py 2 App.py 在Database.py中,我有以下代码: books = [] 在App.py中,我有以下代码: def prompt_read_book(): book_to_search = input("Write the NAME of the book you wa

我刚刚开始学习Python,我有一个关于FOR循环的问题,以及如何使其循环,直到他在列表中找到一个特定元素,然后在不迭代其他列表元素的情况下使其停止:

我创建了两个python文件:1 Database.py 2 App.py

在Database.py中,我有以下代码:

books = []
在App.py中,我有以下代码:

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)
当我的图书列表中有超过1本书2本或更多时,我编写的函数无法按预期工作

例如:

books = [{"name": "Fight Club", "author": "Chuck Palahniuk", "read": False}, {"name": "Homo Deus", "author": "Yuval Noah Harari", "read": False}]
我想把这本名为搏击俱乐部的书标为只读。 所以我输入了搏击俱乐部的名字。 book_to_搜索变量变为:搏击俱乐部 函数正确运行并将{read:False}更改为{read:True}

然而

因为我在for循环中,所以它会不断迭代并打印: 很抱歉,数据库中没有Homo Deus这本书 我对这个问题的理解如下:由于我们处于for循环中,程序会逐个检查列表中的所有元素,以确定它们是否与用户编写的输入匹配。因此,我需要一种在找到匹配元素后停止for循环的方法

我想要的是:

-一旦book_to_搜索与字典的元素匹配,for循环必须停止,而不迭代其他列表的元素

-如果book_to_search与字典中的任何元素不匹配,我想打印抱歉,但是book{book_to_search}不在数据库中

找到该书后添加一个中断,并向检测是否找到该书的变量声明True或False:

def prompt_read_book():
    book_to_search = input("Write the NAME of the book you want to mark as 'READ':\n")
    found = False
    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)
            found = True
            break

    if not found:
        print(f"Sorry but the book {book_to_search} is not in the database")
        print("-" * 40)

编辑:我刚刚编辑了我的答案,因为我误读了最后一部分。现在它只会打印抱歉,但是。。。如果找不到。

你在找声明吗?看,这仍然会打印出之前每本书的抱歉信息。@Barmar哎呀,我看错了问题的最后一部分。我理解中断建议,我试过了,非常感谢。然而,如果我设置了中断,我会遇到另一个问题。基本上,如果我想在列表的第二个或第三个etc.元素中从{read:False}更改为{read:True},我会打印字符串抱歉,但是图书{book\u to\u search}不在数据库中,因为第一个元素已经被迭代,即使它与用户编写的内容不匹配。@FBSO请检查我刚才所做的编辑。希望这能解决问题。就你所说的把读变为真。。。“你是说在这本书的所有事件上吗?”“是的,在所有事件上。您所做的编辑解决了该问题。谢谢