2017-02-26 102 views
0

我想实现一个小型的图书馆管理系统使用python。我们有一个功能列表。我坚持的功能是这部分:简单的图书馆管理系统使用python

  • 实现一个Python函数,该函数将一本书添加到库中。 您的功能应该要求书籍ISBN,书名,作者以及购买了多少份。该功能应更新库存库(词典)以包含新书。 如果该书已在图书馆中,系统应更新数量。

我的字典如下。重点= ISBN,值=拷贝/题名/作者

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

尝试写功能就像这样:

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 
+0

记得要保存返回值'library'到DB(任何种类的数据库使用的是带),否则你下次获得'库dict'时间,它和以前一样,没有任何改变。 –

+0

感谢怪异的蜂蜜,完美的工作。 – vinnievienna