我正在通過Automate the Boring Stuff,這是第5章中的第二個項目。出於某種原因,我的字典在調用添加項目的函數後變爲「None」一本字典。這是我的代碼:將新鍵添加到列表項中的字典時出錯
def displayInventory(anInventory):
item_total = 0
print("Inventory: \n")
for i, j in anInventory.items():
print(str(j) + " " + i)
item_total += j
print("\nTotal number of items: " + str(item_total))
def addToInventory(inventory, addedItems):
for i in addedItems:
if i in inventory:
inventory[i] += 1
else:
inventory[i] = 1
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
我已經縮小問題的addToInventory功能,因爲displayInventory函數可以使用它自己罰款。如果我在創建inv字典時添加打印語句,它將打印字典。但是,如果在調用addToInventory函數後立即添加打印語句,則會打印「無」。
我非常有信心該功能運行良好,所以我會很感激任何幫助指出我的錯誤。謝謝!
似乎[python]隊列對我來說太快xD –