-1

I am coding a text based adventure game and I am currently working on an inventory system this is the code I have:

Inventory=[]

Combat code
A=random.randint(1, 10)
B=random.randint(1, 10)
If a=b:
  Print('enemy dropped wheat')
  Additem('wheat')


Def additem(item):
  Inventory.append(item)

For I in inventory:
  Print(i)

I want to make it so that if I had two wheat it would print 2 wheat not wheat wheat

The code I tried is:


inventory=[]

def additem(item):
  Inventory.append(item)

def removeitem(item):
  Inventory.remove

Additem('wheat')
Additem('wheat')

for wheat in inventory: 
  removeitem('wheat')
  Additem(wheat + 'wheat')

For I in inventory:
  Print(i)

I expected it to print: 2 wheat but it printed: Wheatwheat Wheatwheatwheat

Trog
  • 1
  • 1
  • Does this answer your question? [How do I count the occurrences of a list item?](https://stackoverflow.com/questions/2600191/how-do-i-count-the-occurrences-of-a-list-item) – JonSG Aug 22 '23 at 13:44

3 Answers3

1

Does this solve your problem?

# inventory = ['a', 'b', 'a', 'c']
for i in set(inventory): 
    print(inventory.count(i), i) 
>> 2 a
>> 1 b
>> 1 c   

As a side note, I think you would highly benefit from using a dictionary as your inventory data structure, since it would allow you to add a counter to each item:

inventory = {} # = {'wheat': 1, 'arrow': 50...}
def AddItem(item):
    try:
        inventory['item']+= 1
    except KeyError: # the item is new in the inventory
        inventory['item'] = 1
jlgarcia
  • 333
  • 6
0

Why not use a dict instead of list, so you can track the item and its quantity ?

inventory = {}

def additem(item):
    if item not in inventory:
        inventory[item] = 1
        return
    inventory[item] += 1
naa-rasooa
  • 11
  • 1
0

you could also use

inventory = ["wheat", "wheat", "apple"] 

count = inventory.count("wheat")

take that to a print statement as followed:

print(f" you now have {count} wheats in your inventory")

You could also customize "inventory elements" to be printed with other elements counted in the future.