Home > Software engineering >  Problem with output for List to Dictionary for Fantasy Game Inventory
Problem with output for List to Dictionary for Fantasy Game Inventory

Time:06-20

I'm working on the Automate the boring stuff with Python book. I get the intended results but I also get an added None value. The instructions are as follows:

List to Dictionary Function for Fantasy Game Inventory:

Imagine that a vanquished dragon’s loot is represented as a list of strings like this:

dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

Write a function named addToInventory(inventory, addedItems), where the inventory parameter is a dictionary representing the player’s inventory (like in the previous project) and the addedItems parameter is a list like dragonLoot. The addToInventory() function should return a dictionary that represents the updated inventory. Note that the addedItems list can contain multiples of the same item. Your code could look something like this:

def addToinventory(inventory, addedItems):

inv = {'gold coin': 42, 'rope': 1}
dragonloot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToinventory(inv, dragonloot)
displayInventory(inv)

The previous program (with your displayInventory() function from the previous project) would output the following:

Inventory:
45 gold coin
1 rope
1 ruby
1 dagger
Total number of items: 48

My code is as follows

def addToinventory(inventory, addedItems):
    for i in addedItems:
        inventory.setdefault(i, 0)
        inventory[i]  = 1
    itotal = 0
    for k, v in inventory.items():
        print(str(v), k)
        itotal  = v
    print('Total number of items', itotal)


inv = {'gold coin': 42, 'rope': 1}
dragonloot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
print(addToinventory(inv, dragonloot))

My output is like this:

45 gold coin
1 rope
1 dagger
1 ruby
Total number of items 48
None

At the end of the output, I have a dangling None . I quite don't understand why?

CodePudding user response:

It is because of the line, print(addToinventory(inv, dragonloot)).

Here, you are trying to print the return value of addToinventory(). And addToinventory() doesn't return anything so you are printing None.

To get rid of None, replace print(addToinventory(inv, dragonloot)) with addToinventory(inv, dragonloot).

  • Related