Reputation: 190
I am doing the very last exercise on http://automatetheboringstuff.com/chapter5/. For some reason I am not able to get the displayInventory(inv)
function to return the correct values outside of the addToInventory()
function.
Here is the code:
def displayInventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
print(str(v) + ' ' + k)
item_total += v
print("Total number of items: " + str(item_total))
def addToInventory(inventory, addedItems):
for k in addedItems:
if k in inventory:
inv[k] = inv[k] + 1
print('You have ' + str(inv[k]) + ' ' + k + 's')
else:
print(k + ' is not in inventory')
inventory.setdefault(k, 1)
print()
displayInventory(inv) #does work
inv = {'gold coin': 42, 'rope': 1}
displayInventory(inv)
print()
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
print()
displayInventory(inv) #Doesn't work
I get the error: AttributeError: 'NoneType' object has no attribute 'items'
It looks like the inv
dictionary is empty. Why it is emptied and why the values are different outside of the function?
Upvotes: 2
Views: 49
Reputation: 1123400
Your addToInventory()
function returns None
, because you don't have a specific return
statement.
Since the function alters the dictionary in place, you should just not use the return value; remove the inv =
part:
# ignore the return value; do not replace `inv` with it
addToInventory(inv, dragonLoot)
Upvotes: 3