我正在尝试使用python实现一个小型库管理系统。我们获得了一个功能列表。我坚持的功能是这部分:
我的字典如下。 Key = ISBN,Values = Copies / Title / Author
library = {4139770544441: [5,'Hello World','John'],
4139770544442: [2,'Red Sky','Mary'],
4139770544443: [8,'The Road','Chris']}
以下是我必须添加一本书的功能:
def add_book(key, amount, library):
for current_key in library.keys():
if current_key == key:
library[current_key] = library[current_key] + amount
# amount updated
# get out of the loop and the function
return
#item doesn't exist in the list, add it with the specified amount
library[key] = amount
#User inputs new book titles
enter_copies = int(input('Please enter number of copies to add: '))
enter_title = input('Please enter the Title of the book: ')
enter_author = input('Please enter the Author of the book: ')
#relates to add_book Function
add_book(enter_book, [enter_copies, enter_title, enter_author], library)
如果是新书,我希望它添加到字典中,如果它是现有书籍,我希望它增加副本数量。然而,正在发生的事情就是将isbn(key)和值添加到最后,无论它是否存在。非常感谢你的帮助。
答案 0 :(得分:1)
尝试编写如下函数:
def add_book(key, amount, library):
current_key = library.keys()
if key in current_key:
library[key][0] += amount[0]
else:
library[key] = amount
return library