This is based upon an exercise in chapter 5 of Automate the Boring Stuff with Python.
This code contains functions addToInventory
which modifies a given inventory of items to add new items as well as update existing items and displayInventory
which displays the items and their values. The main operation is adding the contents of a list dragonloot
to inventory inv
.
I have tried to do this in two ways, one by calling addToInventory
and after that calling displayInventory
. This method leads to errors. Another way I tried was by printing the new inventory values within addtoInventory
. This works fine. Why doesn't the first method work? I have put both the methods as comments within my code, indicated by """ """
.
I know C++ pretty well, but I'm new to Python. Expected result: Inventory: gold coin: 45 rope:1 dagger:1 ruby:1 Total number of items is 48
def addToInventory(inventory, addedItems):
draft = {}
for i in addedItems:
if (i not in draft):
draft[i]=1
else:
draft [i]= draft [i] + 1
for i in draft:
if i not in inventory:
inventory[i]=draft[i]
else:
inventory[i] = inventory[i]+draft[i]
"""for i in inventory:
print(str(inventory[i]) + " " + str(i))"""
def displayInventory(inventory):
print ("Inventory: ")
total=0
for i in inventory.items():
total+=1
print (str(inventory[i])+" "+str(i))
print("Total number of items is"+str(total))
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
"""displayInventory(inv) when I use this line in place of above comment I get errors"""