0

So I want to count up all the values together to make a totalItems var which will be printed underneath the list. the output gives me 5 instead of it all being counter up. Can someone explain me why, not just give the right code.

stuff = {'coins': 5, 'arrows': 42, 'rope': 1}


def getInvent(inventory):

    itemTotal = 0
    print('Inventory:')
    print(str(stuff['coins']) + '  Coins')
    print(str(stuff['arrows']) + ' Arrows')
    print(str(stuff['rope']) + '  Rope')   

    for k, v in stuff.items():
        itemTotal = itemTotal + v
        print('Total number of items: ' + str(itemTotal)) 
        return itemTotal

getInvent(stuff)
James
  • 32,991
  • 4
  • 47
  • 70
Mees
  • 116
  • 3
  • 10

2 Answers2

3

You can turn the for loop into a one-liner with sum() and dict.values():

>>> sum(stuff.values())
48

Explanation:

stuff.values() gives you a list of all the values in the dictionary:

>>> stuff.values()
[1, 5, 42]

sum() adds together all items in an iterable (like a list):

>>> sum([1, 5, 42])
48

Full example:

stuff = {'coins': 5, 'arrows': 42, 'rope': 1}

def getInvent(inventory):
    print('Inventory:')
    print(str(stuff['coins']) + '  Coins')
    print(str(stuff['arrows']) + ' Arrows')
    print(str(stuff['rope']) + '  Rope')   

    itemTotal = sum(inventory.values())
    print('Total number of items: ' + str(itemTotal)) 
    return itemTotal

getInvent(stuff)
Julien
  • 5,243
  • 4
  • 34
  • 35
  • Julien just beat me to this, sum the list of values is the easiest way to do this in a single readable line of code – Mr-F Mar 25 '17 at 19:38
  • Thank you, and I saw something about sum() on stackoverflow, but the thing is, I'm following rules of a book. The rules were not to use sum() since I have not been able to learn that yet. – Mees Mar 26 '17 at 17:06
1

You should not return inside your loop because in that case it returns immediately (in the first iteration of the loop). Instead, put the return outside the loop.

for k, v in stuff.items():
    itemTotal = itemTotal + v
    print('Total number of items: ' + str(itemTotal)) 
return itemTotal

A function will return immediately when it encounters the return statement. So you should ensure that your loop runs in its entirety before returning the value.

nb1987
  • 1,400
  • 1
  • 11
  • 12