dyzma
dyzma

Reputation: 23

Task from Automate Boring Stuff With Python chap. 5

I am a new at learning python with book Automate Boring Stuff With Python by Albert Sweigart.

inventory = {'arrows': 12, 'gold coins': 42, 'rope': 1, 'torches': 6, 'dagger': 1}

From this dictionary I need to make output like this:

Inventory:
12 arrows
42 gold coins
1 rope
6 torches
1 dagger
Total number of items: 62

So far I make something like this and I try to use methods from the book:

inventory = {'arrows': 12, 'gold coins': 42, 'rope': 1, 'torches': 6, 'dagger': 1}

def displayInventory(inventory):
    totalNum = 0
    for k, v in inventory.items():
        print(v, k)
        totalNum = totalNum + sum(inventory.values())
    print("Total items of inventory: ")
    return totalNum

print("Your inventory: ")
print(displayInventory(inventory))

Output:

Your inventory:
12 arrows
42 gold coins
1 rope
6 torches
1 dagger
Total items of inventory:
310

Why my totalNum is so big?

Upvotes: 2

Views: 58

Answers (2)

Sri
Sri

Reputation: 2328

You have 5 elements in the dictionary. Your values are (12 + 42 + 1 + 6 + 1) = 62. 62*5 = 310.

You are taking the sum of all inventory.values() each time you go through an item. If you are doing it within the loop, then it should be

totalNum = totalNum + v

If you want to do it outside the loop, then it should be

def displayInventory(inventory):
    for k, v in inventory.items():
        print(v, k)
    print("Total items of inventory: ")
    return sum(inventory.values())

Upvotes: 0

Shubham Sharma
Shubham Sharma

Reputation: 71689

You are getting totalNum different than expected because in each iteration your are incrementing the value of totalNum by 62 because sum(inventory.values()) will return 62. So after five iterations totalNum will be 310.

Just in case you want more compact version of your code, Use:

print("Inventory:")
print("\n".join(f"{v} {k}"for k, v in inventory.items()))
print("Total number of items:", sum(inventory.values()))

This prints:

Inventory:
12 arrows
42 gold coins
1 rope
6 torches
1 dagger
Total number of items: 62

Upvotes: 0

Related Questions