2 回答
TA贡献1833条经验 获得超4个赞
删除代码:
def delete_book():
user_input = input('Input the name of the book to be deleted: ')
for i,book in enumerate(books):
if book['name'] == user_input:
del books[i]
标记为已读的代码:
def mark_read(): # TODO REVIEW !!!!
book_name = input('Input name of the book: ')
f=0 #flag to see if book is present in dict
for book in books:
if book['name'] == book_name:
f=1
user_input = input('Mark book as read? (y/N): ')
if user_input == 'N' or 'n':
print('No changes were made')
elif user_input == 'Y' or 'y':
book['read']=True
break #if book is found, you can exit the loop early
if f==0:
print('The specified book is not currently in our database.')
TA贡献1802条经验 获得超6个赞
您的代码的问题在于,当您只需要一个字段 () 时,您正在循环字典name。因此,您正在删除具有字典第一个字段的书,但您试图再次删除具有字典下一个字段的条目,这是不可能的。
您不需要遍历字典的所有字段来只比较一个字段。以下作品:
books =[{'name': "Hello", "author": "Arthur"}, {'name': "Hi", "author": "Vicky"}]
user_input = input('Input the name of the book to be deleted: ')
for book in books:
if book['name'] == user_input:
books.remove(book)
print(books)
输入“Hi”时的结果:
[{'name': 'Hello', 'author': 'Arthur'}]
添加回答
举报