首页 > 解决方案 > 如何从while循环更改条件

问题描述

我正在尝试创建一个阅读列表,使用 2 个功能 - 一个用于添加书籍,另一个用于显示书籍。添加书籍功能需要执行,直到用户确认更新完成。以下是代码:

book_list = []

def add_books(books):
    book_record = {}
    completed = "no"
    while completed == "no":
        title = input("Enter title : ")
        author = input("Enter author : ")
        year = input("Enter year of publication : ")
        book_record.update({"title": title, "author": author, "year_publ": year})
        books.append(book_record)
        print(books)
        completed = input("update completed ? yes/no")
    return books


def display_books(books):
    for book in books:
        title = book["title"]
        author = book["author"]
        year = book["year_publ"]
        print(f"{title}, {author}, {year}")


option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")

while option != "q" :
    if option == "a":
        book_list = add_books(book_list)
    elif option == "d":
        display_books(book_list)
    else:
        print("Invalid Option")
        option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")

当我执行此代码时,While 循环会忽略已完成的条件并继续要求添加更多书籍,即使用户确认更新已完成。

怎么了 ?我知道我正在尝试在循环内更新完成,这可能就是原因。有什么选择 ?

感谢任何帮助。

谢谢并恭祝安康

萨钦

标签: python

解决方案


所以问题出在option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :"). 您只要求一次选项,您需要的是一个无限循环来继续要求新选项。在您的方法中,当“用户”选择“a”选项时,他/她再也不会被问到,因此选项仍然保留在“a”上,因此add_books()功能运行无止境!

您应该将最后一部分更改为:

while True:
    option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")

    if option == "a":
        book_list = add_books(book_list)
    elif option == "d":
        display_books(book_list)
    elif option == "q":
        quit()
    else:
        print("Invalid Option")


推荐阅读