python - 如何从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 循环会忽略已完成的条件并继续要求添加更多书籍,即使用户确认更新已完成。
怎么了 ?我知道我正在尝试在循环内更新完成,这可能就是原因。有什么选择 ?
感谢任何帮助。
谢谢并恭祝安康
萨钦
解决方案
所以问题出在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")
推荐阅读
- csh - 在 csh 中构造 if 语句时出错
- spring-boot - Spring Boot Rest Controller vs Camel rest dsl
- jenkins-job-dsl - ignoreCommitterStrategy 在多分支作业-dsl 生成器作业中不起作用
- sql-server - 无法使用密钥存储提供程序解密列加密密钥:“AZURE_KEY_VAULT”
- python - 最后如何显示总尝试次数?
- javascript - 如何查看 Google Chrome 控制台中触发了哪些事件?
- azure - 即使在授予权限后,AKS 也无法从 ACR 中提取
- html - 带有随机数的 HTML 模板不呈现
- node.js - 每秒异步更新 UI,无需从服务器刷新页面
- php - 如何使用 PHP 按模式拆分单词匹配